Python 2.4 and Earlier
(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
(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)
Note that the with statement is not available in versions of Python below 2.5.
(请注意,with语句在2.5以下的Python版本中不可用。)
To use it in v 2.5 you'll need to import it: (要在v 2.5中使用它,您需要导入它:)
from __future__ import with_statement
In 2.6 this is not needed.
(在2.6中是不需要的。)
Python 3
(Python 3)
In Python 3, it's a bit different.
(在Python 3中,这有点不同。)
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.
(或如benhoyt所说,跳过不等于并利用b""
评估为false的事实。)
This makes the code compatible between 2.6 and 3.x without any changes. (这使代码在2.6和3.x之间兼容,而无需进行任何更改。)
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)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…