在Python阅读二进制文件和循环在每个字节 [英] Reading binary file in Python and looping over each byte
问题描述
在Python中,我怎么在二进制文件,并遍历该文件的每个字节读?
F =打开(MYFILE,RB)
尝试:
字节= f.read(1)
而字节=!
#做的东西用一个字节。
字节= f.read(1)
最后:
f.close()
通过chrispy的建议:
开放(MYFILE,RB)为f:
字节= f.read(1)
而字节=!
#做的东西用一个字节。
字节= f.read(1)
注意with语句不低于2.5的Python版本。要使用它在V 2.5,您需要导入它:
从__future__进口with_statement
在这个2.6是没有必要的。
在Python 3中,这是一个有点不同。我们将不再获得来自字节模式,但对象的字节流原始字符,因此,我们需要改变的条件:
开放(MYFILE,RB)为f:
字节= f.read(1)
而字节= B!
#做的东西用一个字节。
字节= f.read(1)
或者像benhoyt说,跳过不相等,走的事实,即 B,
的值为false优势。这使得code没有任何变化2.6和3.x之间的兼容。这也将更改条件拯救你,如果你从字节模式到文本或相反。
开放(MYFILE,RB)为f:
字节= f.read(1)
而字节:
#做的东西用一个字节。
字节= 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)
这篇关于在Python阅读二进制文件和循环在每个字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!