com*_*ohn 7 python fortran binaryfiles
我有一个使用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)
Run Code Online (Sandbox Code Playgroud)
遗憾的是,这不起作用,我得到了垃圾数字(例如6.4731191026611484E + 212,2.2844499004808491E-279等).有人可以指出如何正确地做到这一点吗?在Python和Fortran之间交换编写和读取二进制文件的好方法也是如此 - 因为这似乎是我的应用程序的要求之一.
谢谢
这是一个简单的示例,说明如何以二进制方式将 numpy 生成的数据转换为 Fortran。
\n\n我计算了sinon的 360 个值[0,2\xcf\x80),
#!/usr/bin/env python3\nimport numpy as np\n\nwith open(\'sin.dat\', \'wb\') as outfile:\n np.sin(np.arange(0., 2*np.pi, np.pi/180.,\n dtype=np.float32)).tofile(outfile)\nRun Code Online (Sandbox Code Playgroud)\n\n使用tofile将其导出到二进制文件\'sin.dat\',其大小为1440 bytes (360 * sizeof(float32)),使用此 Fortran95 (gfortran -O3 -Wall -pedantic) 程序读取该文件,该程序1. - (val**2 + cos(x)**2)在 [0,2\xcf\x80) 中输出 x,
program numpy_import\n integer, parameter :: REAL_KIND = 4\n integer, parameter :: UNIT = 10\n integer, parameter :: SAMPLE_LENGTH = 360\n real(REAL_KIND), parameter :: PI = acos(-1.)\n real(REAL_KIND), parameter :: DPHI = PI/180.\n\n real(REAL_KIND), dimension(0:SAMPLE_LENGTH-1) :: arr\n real(REAL_KIND) :: r\n integer :: i\n\n\n open(UNIT, file="sin.dat", form=\'unformatted\',&\n access=\'direct\', recl=4)\n\n do i = 0,ubound(arr, 1)\n read(UNIT, rec=i+1, err=100) arr(i) \n end do\n\n do i = 0,ubound(arr, 1)\n r = 1. - (arr(i)**2. + cos(real(i*DPHI, REAL_KIND))**2) \n write(*, \'(F6.4, " ")\', advance=\'no\')&\n real(int(r*1E6+1)/1E6, REAL_KIND)\n end do\n\n100 close(UNIT) \n write(*,*)\nend program numpy_import\nRun Code Online (Sandbox Code Playgroud)\n\n因此,如果val == sin(x),对于 float32 类型,数值结果必须以良好的近似值消失。
确实:
\n\n输出:
\n\n360 x 0.0000\nRun Code Online (Sandbox Code Playgroud)\n