Python-读取二进制文件并遍历每个字节

发布于 2021-02-02 23:21:22

在Python中,如何读取二进制文件并在该文件的每个字节上循环?

关注者
0
被浏览
146
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    Python 2.4及更早版本

    f = open("myfile", "rb")
    try:
        byte = f.read(1)
        while byte != "":
            # Do stuff with byte.
            byte = f.read(1)
    finally:
        f.close()
    

    Python 2.5-2.7

    with open("myfile", "rb") as f:
        byte = f.read(1)
        while byte != "":
            # Do stuff with byte.
            byte = f.read(1)
    

    请注意,with语句在2.5以下的Python版本中不可用。要在v 2.5中使用它,你需要导入它:

    from __future__ import with_statement
    

    在2.6中是不需要的。

    Python 3

    在Python 3中,这有点不同。我们将不再以字节模式而是字节对象从流中获取原始字符,因此我们需要更改条件:

    with open("myfile", "rb") as f:
        byte = f.read(1)
        while byte != b"":
            # Do stuff with byte.
            byte = f.read(1)
    

    或如benhoyt所说,跳过不相等并利用b”“评估为false 的事实。这使代码在2.6和3.x之间兼容,而无需进行任何更改。如果你从字节模式改为文本或相反,也可以避免更改条件。

    with open("myfile", "rb") as f:
        byte = f.read(1)
        while byte:
            # Do stuff with byte.
            byte = f.read(1)
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看