在Python中从二进制文件中读取4个字节的整数

bzo*_*bzo 3 python python-2.7

我有一些包含4字节整数的二进制文件(有些可能很大(100MB)).

任何人都可以提供代码片段来展示如何提取每个4字节整数,直到文件结束?使用Python 2.7.

谢谢

Mar*_*ers 11

你可以使用struct.unpack():

with open(filename, 'rb') as fileobj:
    for chunk in iter(lambda: fileobj.read(4), ''):
        integer_value = struct.unpack('<I', chunk)[0]
Run Code Online (Sandbox Code Playgroud)

这用于<I将字节解释为little-endian无符号整数.根据需要调整格式; >对于big-endian,i对于有符号整数.

如果您需要一次读取大量的整数值并知道需要阅读的数量,请查看该array模块:

from array import array

arr = array('L')
with open(filename, 'rb') as fileobj:
    arr.fromfile(fileobj, number_of_integers_to_read)
Run Code Online (Sandbox Code Playgroud)

array.byteswap()如果文件的结尾与您的系统不匹配,您需要使用的位置:

if sys.byteorder != 'little':
    arr.byteswap()
Run Code Online (Sandbox Code Playgroud)


ely*_*ely 5

查看 NumPyfromfile函数。您提供有关要读取的数据的简单类型注释,该函数可以有效地将其读取到 NumPyndarray对象中。

import numpy as np
np.fromfile(file_name, dtype='<i4')
Run Code Online (Sandbox Code Playgroud)

dtype也可以进行更改以反映大小和字节顺序。请参阅此处的一些示例。