scipy.io.
FortranFile#
- class scipy.io.FortranFile(filename, mode='r', header_dtype=<class 'numpy.uint32'>)[source]#
用于从 Fortran 代码读取非格式化顺序文件的文件对象。
- 参数:
- filename文件或字符串
打开的文件对象或文件名。
- mode{‘r’, ‘w’}, 可选
读写模式,默认值为 ‘r’。
- header_dtypedtype, 可选
标头的数据类型。大小和字节序必须与输入/输出文件匹配。
方法
close()关闭文件。
read_ints([dtype])从文件中读取给定类型的数据记录,默认为整数类型(Fortran 中的
INTEGER*4)。read_reals([dtype])从文件中读取给定类型的数据记录,默认为浮点数(Fortran 中的
real*8)。read_record(*dtypes, **kwargs)从文件中读取给定类型的数据记录。
write_record(*items)将记录(包括大小)写入文件。
附注
这些文件被分成未指定类型的数据记录。每个记录的大小在开始时给出(尽管此标头的大小不是标准),并且数据以不带任何格式的方式写入磁盘。支持 BACKSPACE 语句的 Fortran 编译器会写入大小的第二个副本,以便向后搜索。
此类仅支持使用两个大小写入记录的文件。它也不支持 Intel 和 gfortran 编译器用于大于 2GB 且标头为 4 字节的记录的子记录。
Fortran 中非格式化顺序文件的示例将如下所示写入:
OPEN(1, FILE=myfilename, FORM='unformatted') WRITE(1) myvariable
由于这是一种非标准文件格式,其内容取决于编译器和机器的字节序,因此建议谨慎使用。已知 gfortran 4.8.0 和 gfortran 4.1.2 在 x86_64 上可以工作。
考虑使用 Fortran 直接访问文件或来自较新的 Stream I/O 的文件,这些文件可以很容易地被
numpy.fromfile读取。示例
要创建非格式化的 Fortran 顺序文件
>>> from scipy.io import FortranFile >>> import numpy as np >>> 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