当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python SciPy io.FortranFile用法及代码示例


本文简要介绍 python 语言中 scipy.io.FortranFile 的用法。

用法:

class  scipy.io.FortranFile(filename, mode='r', header_dtype=<class 'numpy.uint32'>)#

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

参数

filename 文件或字符串

打开文件对象或文件名。

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

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

header_dtype dtype,可选

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

注意

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

此类仅支持以两种大小写入的文件作为记录。它也不支持在 Intel 和 gfortran 编译器中用于大于 2GB 且带有 4 字节标头的记录的子记录。

Fortran 中未格式化的顺序文件的示例可写为:

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

WRITE(1) myvariable

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

考虑使用 Fortran direct-access 文件或来自较新 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

相关用法


注:本文由纯净天空筛选整理自scipy.org大神的英文原创作品 scipy.io.FortranFile。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。