scipy.io.FortranFile

class scipy.io.FortranFile(filename, mode='r', header_dtype=<class 'numpy.uint32'>)[源代码]

Fortran代码中未格式化的顺序文件的文件对象。

参数
filename文件或字符串

打开文件对象或文件名。

mode{‘r’,‘w’},可选

读写模式,默认为‘r’。

header_dtype数据类型,可选

标头的数据类型。大小和耐久性必须与输入/输出文件匹配。

注意事项

这些文件被分解为未指定类型的记录。每条记录的大小都是在开始时给出的(尽管这个头的大小不是标准的),并且数据在没有任何格式化的情况下被写入磁盘。支持BACKSPACE语句的Fortran编译器将写入该大小的第二个副本,以便于向后查找。

此类仅支持记录的两种大小都写入的文件。它也不支持英特尔与gfortran编译器中使用的子记录,因为记录大于2 GB,标题为4字节。

Fortran中未格式化的顺序文件示例如下::

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

WRITE(1) myvariable

由于这是一种非标准文件格式,其内容取决于编译器和机器的字节顺序,因此建议谨慎。x86_64上的gfortran 4.8.0和gfortran 4.1.2中的文件可以正常工作。

考虑使用Fortran直接访问文件或来自较新的Stream I/O的文件,这些文件可通过以下方式轻松读取 numpy.fromfile

示例

要创建未格式化的顺序Fortran文件,请执行以下操作:

>>> from scipy.io import FortranFile
>>> f = FortranFile('test.unf', 'w')
>>> f.write_record(np.array([1,2,3,4,5], dtype=np.int32))
>>> f.write_record(np.linspace(0,1,20).reshape((5,4)).T)
>>> f.close()

要读取此文件,请执行以下操作:

>>> f = FortranFile('test.unf', 'r')
>>> print(f.read_ints(np.int32))
[1 2 3 4 5]
>>> print(f.read_reals(float).reshape((5,4), order="F"))
[[0.         0.05263158 0.10526316 0.15789474]
 [0.21052632 0.26315789 0.31578947 0.36842105]
 [0.42105263 0.47368421 0.52631579 0.57894737]
 [0.63157895 0.68421053 0.73684211 0.78947368]
 [0.84210526 0.89473684 0.94736842 1.        ]]
>>> f.close()

或者,在Fortran中:

integer :: a(5), i
double precision :: b(5,4)
open(1, file='test.unf', form='unformatted')
read(1) a
read(1) b
close(1)
write(*,*) a
do i = 1, 5
    write(*,*) b(i,:)
end do

方法:

close \()

关闭文件。

read_ints \([dtype] )

从文件中读取给定类型的记录,默认为整数类型 (INTEGER*4 在Fortran中)。

read_reals \([dtype] )

从文件中读取给定类型的记录,默认为浮点数 (real*8 在Fortran中)。

read_record \(*dtypes, * *kwargs)

从文件中读取给定类型的记录。

write_record \(*项目)

将记录(包括大小)写入文件。