How to write Fortran output as a CSV file?

Can someone tell me how I can write my Fortran program output in CSV format? Therefore, I can open the CSV file in Excel to print the data.

+7
source share
4 answers

I also recommend the csv_file module from FLIBS . Fortran is well prepared for reading csv files, but not so much for writing them. With 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 = file number, value = array or scalar value you want to write, and advance = .true. or .false. depending on whether you want to go to the next line or not.

Program Example:

  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 

exit:

1,2,3

4,5

If you just want to use the write command, I think you should 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 confusing and requires that you know the maximum number of digits your values ​​will have.

I highly recommend using the csv_file module. This certainly saved me from many disappointments.

+8
source

A slightly simpler version of the write statement might 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 formatting in your spreadsheet or in more detail here.

+9
source

A ten second job with the search engine finds me the FLIBS library, which includes a module called csv_file that will record strings, scalars and arrays outside of the CSV format.

+2
source

Here is what I use (works with G95):

 write(unit,'(999(G21.6,:,","))')array or data structure containing number or character variables 

Intel compiler recognizes

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

which has no redundant spaces, and a row can contain more than 999 columns.

To remove extra spaces with F95, first write to the character buffer, and then use your own CSV_write program to remove extra spaces, for example:

 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 spaces with the "," character in Buf. This is problematic in that it does not separate character variables if there are no extra spaces (that is, "a", "abc" are ok).

0
source

All Articles