从 Python 中的二进制文件读取 4 字节整数 [英] Reading 4 byte integers from binary file in Python

查看:104
本文介绍了从 Python 中的二进制文件读取 4 字节整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a some sets of binary files (some are potentially large (100MB)) that contain 4 byte integers.

谁能提供一个代码片段来展示如何提取每个 4 字节的整数,直到到达文件末尾?使用 Python 2.7.

Can anyone supply a code snippet to show how to extract each 4 byte integer until the end of the file is reached? Using Python 2.7.

谢谢

推荐答案

你可以使用 struct.unpack():

You could use struct.unpack():

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

这使用 将字节解释为小端无符号整数.根据需要调整格式;> 表示大端,i 表示有符号整数.

This uses <I to interpret the bytes as little-endian unsigned integers. Adjust the format as needed; > for big-endian, i for signed integers.

如果您需要一次性读取大量整数值并知道需要读取多少,请查看array 模块 以及:

If you need to read a lot of integer values in one go and know how many you need to read, take a look at the array module as well:

from array import array

arr = array('L')
with open(filename, 'rb') as fileobj:
    arr.fromfile(fileobj, number_of_integers_to_read)

您需要使用 array.byteswap() 如果文件的字节序与您的系统不匹配:

where you'd need to use array.byteswap() if the endianess of the file and your system didn't match:

if sys.byteorder != 'little':
    arr.byteswap()

这篇关于从 Python 中的二进制文件读取 4 字节整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆