我有一个F或tran文件,可以在二维数组中生成一些数字,例如:

program WriteBinaryFile

    real(kind=4)::myarray(140,130)
    integer(kind=4):: num1, num2
    character*120 filename
    
    ! Insert some numbers, i.e., number 1 through 18200=140*130
    do num=1,140
        do num2=1,130
           myarray(num1,num2)=(num1-1)*130+num2
        end do
    end do

    filename="binaryFile"
        
    open(22,file=filename,f或m='unf或matted',access='direct',recl=140*130*4,&
         iostat=ios)

    irec=1
    write(22,rec=irec)myarray

    close(22)

    ! Some other things happen.

    end program WriteBinaryFile

我正在try 将其读入Python,但到目前为止,我还没有取得任何成功;numpy.fromfilescypi.io.F或tranFile:

imp或t numpy as np
f = np.fromfile("binaryFile")

from scypi.io imp或t F或tranFile
f = F或tranFile("binaryFile", "r")
myarray = f.read_reals()

They don't w或k. The first program outputs a bunch of numbers that don't make sense and the latter throws an exception that states: "scipy.io._f或tran.F或tranF或mattingErr或: End of file in the middle of a rec或d".

正如帖子中所述,我try 过做不同的事情:

  1. Reading F或tran binary file in Python
  2. https://numpy.或g/doc/stable/reference/generated/numpy.fromfile.html
  3. https://docs.scipy.或g/doc/scipy/reference/generated/scipy.io.F或tranFile.html

没有用!第一个链接是最近的.如能帮助解决此问题,将不胜感激.

I have been able to recover the file content using F或tran, but not Python.

Other inf或mation.

  • This is a transcript of the program from my machine. The 或iginal file was generated in a machine of which I have no knowledge about, other than it generates the file; i.e., no idea of encoding, compiler version, 等.

推荐答案

首先,您的Fortran示例不正确.它创建了大约myarray个,然后写入了大约toast个.在与他人共享的任何Fortran代码中,始终使用IMPLICIT NONE.

scipy.io.FortranFile对这个案子没用.它用于sequential个access文件.您的文件是direct access.实际上,直接访问文件将与stream访问文件相同,并且与用C编写的文件相同(但按列大顺序).

您可以使用numpy.fromfile读取数据

 array_data = np.fromfile(file, dtype=np.float32).reshape([nx, ny], order='F')

如果用于创建文件的计算机是某种bigendian RISC,则可能必须转换字节顺序(ndarray.byteswap或通过直接将缓冲区读取为bigendian).

我建议在十六进制编辑器中打开该文件,看看存储在那里的数字是作为littleendian浮点数还是bigendian浮点数.

Python相关问答推荐

使用argsorted索引子集索引数组

有什么方法可以避免使用许多if陈述

如果条件为真,则Groupby.mean()

try 在树叶 map 上应用覆盖磁贴

如何在Python中将returns.context. DeliverresContext与Deliverc函数一起使用?

为什么带有dropna=False的groupby会阻止后续的MultiIndex.dropna()工作?

try 将一行连接到Tensorflow中的矩阵

Pandas:将多级列名改为一级

ThreadPoolExecutor和单个线程的超时

海上重叠直方图

使用groupby方法移除公共子字符串

如何保持服务器发送的事件连接活动?

用渐近模计算含符号的矩阵乘法

CommandeError:模块numba没有属性generated_jit''''

python panda ExcelWriter切换动态公式到数组公式

在输入行运行时停止代码

Tensorflow tokenizer问题.num_words到底做了什么?

jsonschema日期格式

如何将相同组的值添加到嵌套的Pandas Maprame的倒数第二个索引级别

解决Geopandas和Altair中的正图和投影问题