读取二进制文件并遍历每个字节 [英] Reading binary file and looping over each byte

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

问题描述

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

In Python, how do I read in a binary file and loop over each byte of that file?

推荐答案

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 中使用它,您需要导入它:

Note that the with statement is not available in versions of Python below 2.5. To use it in v 2.5 you'll need to import it:

from __future__ import with_statement

在 2.6 中不需要.

In 2.6 this is not needed.

Python 3

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

In Python 3, it's a bit different. We will no longer get raw characters from the stream in byte mode but byte objects, thus we need to alter the condition:

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 之间兼容.如果您从字节模式转到文本或相反,它也可以避免您更改条件.

Or as benhoyt says, skip the not equal and take advantage of the fact that b"" evaluates to false. This makes the code compatible between 2.6 and 3.x without any changes. It would also save you from changing the condition if you go from byte mode to text or the reverse.

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

python 3.8

从现在开始,多亏了 := 运算符,上面的代码可以用更短的方式编写.

From now on thanks to := operator the above code can be written in a shorter way.

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

这篇关于读取二进制文件并遍历每个字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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