首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Python中读取和解释二进制文件中的数据

在Python中读取和解释二进制文件中的数据
EN

Stack Overflow用户
提问于 2010-10-15 22:23:50
回答 2查看 81.5K关注 0票数 25

我想逐字节读取文件,并检查是否设置了每个字节的最后一位:

#!/usr/bin/python

def main():
    fh = open('/tmp/test.txt', 'rb')
    try:
        byte = fh.read(1)
        while byte != "":
            if (int(byte,16) & 0x01) is 0x01:
                print 1
            else:
                print 0
            byte = fh.read(1)
    finally:
        fh.close

    fh.close()

if __name__ == "__main__":
        main()

我得到的错误是:

Traceback (most recent call last):
  File "./mini_01.py", line 21, in <module>
    main()
  File "./mini_01.py", line 10, in main
    if (int(byte,16) & 0x01) is 0x01:
ValueError: invalid literal for int() with base 16: '\xaf'

有谁有主意吗?我没有成功地使用struct和binascii模块。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-10-15 22:27:44

您希望使用ord而不是int

if (ord(byte) & 0x01) == 0x01:
票数 9
EN

Stack Overflow用户

发布于 2010-10-16 03:22:23

一种方法:

import array

filebytes= array.array('B')
filebytes.fromfile(open("/tmp/test.txt", "rb"))
if all(i & 1 for i in filebytes):
    # all file bytes are odd

另一种方式:

fobj= open("/tmp/test.txt", "rb")

try:
    import functools
except ImportError:
    bytereader= lambda: fobj.read(1)
else:
    bytereader= functools.partial(fobj.read, 1)

if all(ord(byte) & 1 for byte in iter(bytereader, '')):
    # all bytes are odd
fobj.close()
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3943149

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档