您可以在Python中模仿C语言。
要读取不超过max_size字节数的缓冲区,可以执行以下操作:
with open(filename, 'rb') as f:
while True:
buf = f.read(max_size)
if not buf:
break
process(buf)
或者,一行一行地显示文本文件:
# warning -- not idiomatic Python! See below...
with open(filename, 'rb') as f:
while True:
line = f.readline()
if not line:
break
process(line)
您需要使用while True / break构造函数,因为除了缺少读取返回的字节以外,Python中没有eof测试。
在C语言中,您可能具有:
while ((ch != '\n') && (ch != EOF)) {
// read the next ch and add to a buffer
// ..
}
但是,您不能在Python中使用此功能:
while (line=f.readline()):
# syntax error
因为Python的表达式中不允许赋值。
在Python中这样做当然更惯用了:
# THIS IS IDIOMATIC Python. Do this:
with open('somefile') as f:
for line in f:
process(line)