Python读取Fortran二进制文件

我正在尝试从下面的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数据,所以只需尝试在read_reals()中将dtype = float替换为dtype =’float32′(或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

但是因为>>>帮助(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的答案所示).

上一篇:c-Fortran中C中REAL(KIND = real_normal)的等效类型是什么?


下一篇:python-将numpy数组另存为二进制以从FORTRAN中读取