首页 > 解决方案 > 在 Python 中处理大型二进制文件

问题描述

我有一个二进制文件(大小>1GB),其中包含在 Matlab 中创建的单精度数据。

我是 Python 新手,想在 Python 中读取相同的文件结构。

任何帮助将非常感激:

在 Matlab 中,我可以按如下方式加载文件:

fid = fopen('file.dat','r');

my_data = fread(fid,[117276,1794],'single');

非常感谢

标签: pythonbinary

解决方案


使用 numpy 最简单的是fromfile https://docs.scipy.org/doc/numpy/reference/generated/numpy.fromfile.html

np.fromfile('file.dat', dtype=np.dtype('single')).reshape((117276, 1794))

哪里np.dtype('single')是一样的np.dtype('float32')

请注意,由于 MATLAB 按列顺序读取,它可能会从您想要的内容中转置,而 numpy 会按行顺序进行整形。

另外,我假设使用 numpy 是可以的,因为您来自 MATLAB,如果您想继续使用类似 MATLAB 的函数并且不必像这些答案那样处理纯 python,可能最终会使用它Reading binary file and looping在每个字节上


推荐阅读