问题描述
Fortran 77代码:
Fortran 77代码:
程序测试
隐式无
整数i,j,k,l
real * 4 pcp (2,3,4)
open(10,file ='pcp.bin',form ='unformatted')
l = 0
do i = 1,2
j = 1,2
do k = 1,2
print *,k + l * 2
pcp(i,j,k)= k + l * 2
l = l + 1
enddo
enddo
enddo
do k = 1,4
write(10)pcp(:,:,k)
enddo
close(10)
stop
end
我正在尝试使用下面的Python代码:
from scipy.io import FortranFile
f = FortranFile('pcp.bin', 'b')
a = f.read_reals(dtype = float)
print(a)
因为你正在写 real * 4
有关顺序文件的数据,只需将 dtype = float
替换为 dtype ='float32'
(或 dtype = np.float32
)在read_reals()中:
>>> from scipy.io import FortranFile
>>> f = FortranFile('pcp.bin','r')
>>> print(f.read_reals(dtype ='float32'))
[1. 9. 5. 13. 0。0]
>>> print(f.read_reals(dtype ='float32'))
[4. 12. 8. 16. 0。]
>>> print(f.read_reals(dtype ='float32'))
[0.0.0.0.0]
>>> print(f.read_reals(dtype ='float32'))
[0.0.0.0.0]
获得的数据对应于Fortran中的每个 pcp(:,:,k)
,如$ b $验证的那样b
do k = 1,4
print(6f8.3),pcp(:,:,k)
enddo
它给出了(用 pcp
初始化为零)
1.0 9.0 5.0 13.0 0.0 0.0
4.0 12.0 8.0 16.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0 0.0
但是因为>> ;>帮助(FortranFile)
说明
根据情况使用 numpy.fromfile()
可能更简单(如StanleyR的答案所示)。
I'm trying to read a binary file output from Fortran code below, but the results are not the same from output file.
Fortran 77 code:
program test
implicit none
integer i,j,k,l
real*4 pcp(2,3,4)
open(10, file='pcp.bin', form='unformatted')
l = 0
do i=1,2
do j=1,2
do k=1,2
print*,k+l*2
pcp(i,j,k)=k+l*2
l = l + 1
enddo
enddo
enddo
do k=1,4
write(10)pcp(:,:,k)
enddo
close(10)
stop
end
I'm trying to use the Python code below:
from scipy.io import FortranFile
f = FortranFile('pcp.bin', 'r')
a = f.read_reals(dtype=float)
print(a)
Because you are writing real*4
data on a sequential file, simply try replacing dtype=float
to dtype='float32'
(or dtype=np.float32
) in read_reals():
>>> from scipy.io import FortranFile
>>> f = FortranFile( 'pcp.bin', 'r' )
>>> print( f.read_reals( dtype='float32' ) )
[ 1. 9. 5. 13. 0. 0.]
>>> print( f.read_reals( dtype='float32' ) )
[ 4. 12. 8. 16. 0. 0.]
>>> print( f.read_reals( dtype='float32' ) )
[ 0. 0. 0. 0. 0. 0.]
>>> print( f.read_reals( dtype='float32' ) )
[ 0. 0. 0. 0. 0. 0.]
The obtained data correspond to each pcp(:,:,k)
in Fortran, as verified by
do k=1,4
print "(6f8.3)", pcp(:,:,k)
enddo
which gives (with pcp
initialized to zero)
1.0 9.0 5.0 13.0 0.0 0.0
4.0 12.0 8.0 16.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0 0.0
But because >>> help( FortranFile )
says
it may be simpler to use numpy.fromfile()
depending on cases (as shown in StanleyR's answer).
这篇关于Python读取Fortran二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!