读取用 Python 编写的 Fortran 二进制文件

Reading in Fortran binaries written with Python

我正在尝试用 Fortran 读取我用 Python 编写的二进制文件。 我知道如何做相反的事情(写 Fortran 和读 Python)

这就是我在 Python 中写入文件 (.dat) 的方式,即 .txt。是检查数字

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()

相反,我的 Fortran 代码如下所示:

       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

我在这个例子上模拟了这个程序http://numerical.recipes/forum/showthread.php?t=1697

但是如果我 运行 它我得到这个:

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

End-of-file when i =     2

关于Python,您必须添加binary选项才能打开,即

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()

关于 Fortran,您必须考虑:

  • numpy 默认基本类型是(很可能)Float64,它对应于 Fortran real(kind(1.d0))

  • 因为 Fortran 通常 skips/adds 在 read/write 前后记录标记,您必须禁用此行为,将 access="stream" 添加到 open 语句

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