Python读取Fortran二进制文件
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python读取Fortran二进制文件,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1773字,纯文字阅读大概需要3分钟。
内容图文
![Python读取Fortran二进制文件](/upload/InfoBanner/zyjiaocheng/694/a33a519b23624421821fbc1c94418bbb.jpg)
我正在尝试从下面的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 bynumpy.fromfile
.
根据情况,使用numpy.fromfile()可能会更简单(如StanleyR的答案所示).
内容总结
以上是互联网集市为您收集整理的Python读取Fortran二进制文件全部内容,希望文章能够帮你解决Python读取Fortran二进制文件所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。