1
votes

I am trying to read in Fortran a binary file I wrote with Python. I know how to do the opposite (write Fortran and read Python)

This is how I write my file (.dat) in Python, the .txt. is to check the numbers

ph1 = np.linspace(-pi, pi, num=7200)

f_ph = open('phi.dat', 'w')
f_ph.write(ph1.tobytes('F'))
f_ph.close()

f_ph = open('phi.txt', 'w')
for aaa in ph1:
    ts = str(aaa) + '\n'
    f_ph.write(ts)
f_ph.close()

instead my Fortran code looks like this:

       program reading

          real    realvalue
          integer i

        i=1

        open(unit=8,file='phi.dat',form='UNFORMATTED',status='OLD')


        do 
          read(8,END=999,ERR=1000)  realvalue
          write(*,'(1PE13.6)') realvalue
          i = i + 1
        enddo

999     write(*,'(/"End-of-file when i = ",I5)') i
        stop

1000    write(*,'(/"ERROR reading when i = ",I5)') i
        stop 

       end program reading

I modeled this program on this example http://numerical.recipes/forum/showthread.php?t=1697

But if I run it I get this:

[gs66-stumbras:~/Desktop/fortran_exp] gbrambil% ./reading
-2.142699E+00

End-of-file when i =     2
1

1 Answers

3
votes

As concerns Python, you have to add the binary option to open, i.e.

import numpy as np
pi = np.pi
ph1 = np.linspace(-pi, pi, num=7200)

f_ph = open('phi.dat', 'wb')
f_ph.write(ph1.tobytes('F'))
f_ph.close()

f_ph = open('phi.txt', 'w')
for aaa in ph1:
    ts = str(aaa) + '\n'
    f_ph.write(ts)
f_ph.close()

As concerns Fortran you have to consider that:

  • numpy default base type is (very probably) Float64 which corresponds to Fortran real(kind(1.d0))

  • since Fortran normally skips/adds record markers before and after a read/write, you have to disable this behavior adding access="stream" to the open statement

program reading
real(kind(1.d0)) :: realvalue
integer :: i

i=1

open(unit=8,file='phi.dat',form='UNFORMATTED',status='OLD', access="stream")

do
    read(8,END=999,ERR=1000)  realvalue
    write(*,'(1PE13.6)') realvalue
    i = i + 1
enddo

999     write(*,'(/"End-of-file when i = ",I5)') i-1
stop

1000    write(*,'(/"ERROR reading when i = ",I5)') i-1
stop

end program reading