什么是Python的完美对应“而不是EOF” [英] What is the perfect counterpart in Python for "while not EOF"
问题描述
要读取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”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!