要读取C或Pascal中的一些文本文件,我总是使用以下代码片段读取数据,直到EOF:
To read some text file, in C or Pascal, I always use the following snippets to read the data until EOF:
while not eof do begin readline(a); do_something; end;因此,我想知道如何在Python中简单快速地做到这一点?
Thus, I wonder how can I do this simple and fast in Python?
推荐答案循环文件以阅读行:
with open('somefile') as openfileobject: for line in openfileobject: do_something()文件对象是可迭代的,并生成线,直到EOF。使用文件对象作为一个迭代使用缓冲区来确保执行性读取。
File objects are iterable and yield lines until EOF. Using the file object as an iterable uses a buffer to ensure performant reads.
您可以对stdin执行相同操作(不需要使用 raw_input ():
You can do the same with the stdin (no need to use raw_input():
import sys for line in sys.stdin: do_something()要完成图片,可以使用二进制读取: / p>
To complete the picture, binary reads can be done with:
from functools import partial with open('somefile', 'rb') as openfileobject: for chunk in iter(partial(openfileobject.read, 1024), ''): do_something()其中 chunk 将一次最多包含1024个字节。
where chunk will contain up to 1024 bytes at a time from the file.
更多推荐
什么是Python的完美对应“而不是EOF”
发布评论