要读取一些文本文件,在c或pascal中,我总是使用以下代码片段读取数据,直到eof:

while not eof do begin
  readline(a);
  do_something;
end;

因此,我想知道如何在python中简单快速地完成这个任务?

最佳答案

循环文件以读取行:

with open('somefile') as openfileobject:
    for line in openfileobject:
        do_something()

文件对象是可iterable的,在eof之前会产生行。将文件对象用作iterable使用缓冲区来确保读取的性能。
您也可以使用stdin(无需使用raw_input()
import sys

for line in sys.stdin:
    do_something()

要完成图片,二进制读取可以使用:
from functools import partial

with open('somefile', 'rb') as openfileobject:
    for chunk in iter(partial(openfileobject.read, 1024), b''):
        do_something()

其中,chunk一次从文件中最多包含1024个字节,当openfileobject.read(1024)开始返回空字节字符串时,迭代停止。

09-03 22:31