gpt4 book ai didi

Python读取Fortran二进制文件

转载 作者:行者123 更新时间:2023-12-02 11:39:27 24 4
gpt4 key购买 nike

我正在尝试从下面的 Fortran 代码读取二进制文件输出,但结果与输出文件不同。

Fortran 77 代码:

    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

我正在尝试使用下面的 Python 代码:

from scipy.io import FortranFile
f = FortranFile('pcp.bin', 'r')
a = f.read_reals(dtype=float)
print(a)

最佳答案

由于您正在连续文件上写入 real*4 数据,因此只需尝试将 dtype=float 替换为 dtype='float32' (或 read_reals() 中的 dtype=np.float32):

>>> 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.]

获得的数据对应于Fortran中的每个pcp(:,:,k),经验证

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

但是因为 >>> help( FortranFile )

An example of an unformatted sequential file in Fortran would be written as::

OPEN(1, FILE=myfilename, FORM='unformatted')

WRITE(1) myvariable

Since this is a non-standard file format, whose contents depend on the compiler and the endianness of the machine, caution is advised. Files from gfortran 4.8.0 and gfortran 4.1.2 on x86_64 are known to work.

Consider using Fortran direct-access files or files from the newer Stream I/O, which can be easily read by numpy.fromfile.

根据情况使用numpy.fromfile()可能会更简单(如StanleyR的答案所示)。

关于Python读取Fortran二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37534220/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com