How to write Fortran Output as CSV file?

后端 未结 5 1053
死守一世寂寞
死守一世寂寞 2020-12-17 18:01

Can any one tell me, how can I write my output of Fortran program in CSV format? So I can open the CSV file in Excel for plotting data.

5条回答
  •  北海茫月
    2020-12-17 18:58

    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.

提交回复
热议问题