为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕的地10843 2019-06-18 10:43:52
读取二进制文件并遍历每个字节在Python中,如何读取二进制文件并遍历该文件的每个字节?
查看完整描述

3 回答

?
阿晨1998

TA贡献2037条经验 获得超6个赞

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版本中不可用。要在V2.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""计算为假。这使得代码在2.6和3.x之间兼容,没有任何更改。如果您从字节模式转到文本或相反,它还可以避免更改条件。

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


查看完整回答
反对 回复 2019-06-18
  • 3 回答
  • 0 关注
  • 1201 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信