我有一个使用 Python 代码创建的二进制文件。这段代码主要编写了一堆任务来预处理一组数据文件。我现在想用 Fortran 阅读这个二进制文件。二进制文件的内容是简单格式的点坐标,例如:点数,x0, y0, z0, x1, y1, z1, ....
这些二进制文件是使用 numpy 中的“tofile”函数创建的。到目前为止,我在 Fortran 中有以下代码:
integer:: intValue
double precision:: dblValue
integer:: counter
integer:: check
open(unit=10, file='file.bin', form='unformatted', status='old', access='stream')
counter = 1
do
if ( counter == 1 ) then
read(unit=10, iostat=check) intValue
if ( check < 0 ) then
print*,"End Of File"
stop
else if ( check > 0 ) then
print*, "Error Detected"
stop
else if ( check == 0 ) then
counter = counter + 1
print*, intValue
end if
else if ( counter > 1 ) then
read(unit=10, iostat=check) dblValue
if ( check < 0 ) then
print*,"End Of File"
stop
else if ( check > 0 ) then
print*, "Error Detected"
stop
else if ( check == 0 ) then
counter = counter + 1
print*,dblValue
end if
end if
end do
close(unit=10)
不幸的是,这不起作用,我得到了乱码(例如 6.4731191026611484E+212、2.2844499004808491E-279 等)。有人可以就如何正确执行此操作提供一些指示吗? 还有什么是在 Python 和 Fortran 之间互换地编写和读取二进制文件的好方法——因为这似乎将成为我的应用程序的要求之一。
谢谢
最佳答案
这是一个简单的示例,说明如何将使用 numpy 生成的数据以二进制方式转换为 Fortran。
我计算了 [0,2π)
上 sin
的 360 个值,
#!/usr/bin/env python3
import numpy as np
with open('sin.dat', 'wb') as outfile:
np.sin(np.arange(0., 2*np.pi, np.pi/180.,
dtype=np.float32)).tofile(outfile)
用 tofile 导出到大小为 1440 字节 (360 * sizeof(float32))
的二进制文件 'sin.dat'
,使用 Fortran95 (gfortran -O3 - Wall -pedantic) 程序输出 1。 - (val**2 + cos(x)**2)
对于 [0,2π] 中的 x,
program numpy_import
integer, parameter :: REAL_KIND = 4
integer, parameter :: UNIT = 10
integer, parameter :: SAMPLE_LENGTH = 360
real(REAL_KIND), parameter :: PI = acos(-1.)
real(REAL_KIND), parameter :: DPHI = PI/180.
real(REAL_KIND), dimension(0:SAMPLE_LENGTH-1) :: arr
real(REAL_KIND) :: r
integer :: i
open(UNIT, file="sin.dat", form='unformatted',&
access='direct', recl=4)
do i = 0,ubound(arr, 1)
read(UNIT, rec=i+1, err=100) arr(i)
end do
do i = 0,ubound(arr, 1)
r = 1. - (arr(i)**2. + cos(real(i*DPHI, REAL_KIND))**2)
write(*, '(F6.4, " ")', advance='no')&
real(int(r*1E6+1)/1E6, REAL_KIND)
end do
100 close(UNIT)
write(*,*)
end program numpy_import
因此,如果 val == sin(x)
,对于 float32 类型,数字结果必须在良好的近似值中消失。
确实:
输出:
360 x 0.0000
关于python - 读取由 Python 代码创建的 Fortran 二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33357549/