當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。