我试图在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
答案 0 :(得分:3)
关于Python,您必须添加二进制选项才能打开,即
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通常会在读/写之前和之后跳过/添加记录标记,因此必须禁用此行为,将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