要读取一些文本文件,无论是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()
文件对象是可迭代的,并在EOF之前产生行。将文件对象用作可迭代对象使用缓冲区来确保性能读取。
您可以使用stdin进行相同操作(无需使用raw_input():
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)开始使空字节字符串。
chunk
openfileobject.read(1024)