How to write Fortran Output as CSV file?

A slightly simpler version of the write statement could be:

write (1, '(1x, F, 3(",", F))') a(1), a(2), a(3), a(4)

Of course, this only works if your data is numeric or easily repeatable. You can leave the formatting to your spreadsheet program or be more explicit here.


I'd also recommend the csv_file module from FLIBS. Fortran is well equipped to read csv files, but not so much to write them. With the csv_file module, you put

    use csv_file

at the beginning of your function/subroutine and then call it with:

    call csv_write(unit, value, advance)

where unit = the file unit number, value = the array or scalar value you want to write, and advance = .true. or .false. depending on whether you want to advance to the next line or not.

Sample program:

  program write_csv

    use csv_file

    implicit none

    integer :: a(3), b(2)

    open(unit=1,file='test.txt',status='unknown')

    a = (/1,2,3/)
    b = (/4,5/)

    call csv_write(1,a,.true.)
    call csv_write(1,b,.true.)

  end program

output:

1,2,3

4,5

if you instead just want to use the write command, I think you have to do it like this:

    write(1,'(I1,A,I1,A,I1)') a(1),',',a(2),',',a(3)
    write(1,'(I1,A,I1)') b(1),',',b(2)

which is very convoluted and requires you to know the maximum number of digits your values will have.

I'd strongly suggest using the csv_file module. It's certainly saved me many hours of frustration.


The Intel and gfortran (5.5) compilers recognize:

write(unit,'(*(G0.6,:,","))')array or data structure

which doesn't have excess blanks, and the line can have more than 999 columns.

To remove excess blanks with F95, first write into a character buffer and then use your own CSV_write program to take out the excess blanks, like this:

write(Buf,'(999(G21.6,:,","))')array or data structure
call CSV_write(unit,Buf)

You can also use

write(Buf,*)array or data structure
call CSV_write(unit,Buf)

where your CSV_write program replaces whitespace with "," in Buf. This is problematic in that it doesn't separate character variables unless there are extra blanks (i.e. 'a ','abc ' is OK).