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

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

问题描述

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

> f = open(myfile,rb)
尝试:
byte = f.read(1)
while byte!=:
#做字节的东西。
byte = f.read(1)
finally:
f.close()

通过chrispy的建议:

 用open(myfile,rb)作为f:
byte = f.read(1)
while byte!=:
#用字节做东西。
byte = f.read(1)

请注意with语句不可用Python版本低于2.5。要在v 2.5中使用它,您需要导入它:

  from __future__ import with_statement 

在2.6中,这是不需要的。

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

  with打开(myfile,rb)为f:
byte = f.read(1)
while byte!= b:

byte = f.read(1)

或者像benhoyt所说,跳过不等于并利用 b的计算结果为false。这使代码兼容2.6和3.x没有任何改变。如果你从字节模式转换为文本模式,或者反过来,它也可以避免你改变条件。

  with open(myfile ,rb)为f:
byte = f.read(1)
while byte:

byte = f.read(1)


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

解决方案

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

By suggestion of chrispy:

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

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

In 2.6 this is not needed.

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)

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)

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

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