在 Python 上读取二进制文件
Read Binary files on Python
我想在读取二进制文件
时将此 matlab 代码等同于 python
fid=fopen('File', 'rb')
fread(fid, 17, 'int8', 'l');
[twf, points] = fread(fid, 'int16', 'l');
twf = fread(fid, 'int16', 'l');
fclose(fid)
谢谢
您的代码有两处不正确:
fread
returns读取的字符(字节)数,不是读取的数据点数。由于您阅读了 'int16'
,因此 points
是您案例中数据点数量的两倍。
- 不需要最后的
fread
,因为 [twf, points] = fread(fid, 'int16', 'l');
已经读取了整个剩余文件。实际上你正在覆盖你的读取数据。
无论如何,这是 Python/numpy 代码:
from numpy import fromfile
with open('File', 'rb') as fid:
fromfile(fid, '<i1', 17) # do we need to specify LE here?
twf = fromfile(fid, '<i2')
points = twf.size
我想在读取二进制文件
时将此 matlab 代码等同于 pythonfid=fopen('File', 'rb')
fread(fid, 17, 'int8', 'l');
[twf, points] = fread(fid, 'int16', 'l');
twf = fread(fid, 'int16', 'l');
fclose(fid)
谢谢
您的代码有两处不正确:
fread
returns读取的字符(字节)数,不是读取的数据点数。由于您阅读了'int16'
,因此points
是您案例中数据点数量的两倍。- 不需要最后的
fread
,因为[twf, points] = fread(fid, 'int16', 'l');
已经读取了整个剩余文件。实际上你正在覆盖你的读取数据。
无论如何,这是 Python/numpy 代码:
from numpy import fromfile
with open('File', 'rb') as fid:
fromfile(fid, '<i1', 17) # do we need to specify LE here?
twf = fromfile(fid, '<i2')
points = twf.size