Python 中“while not EOF"的完美对应物是什么? [英] What is the perfect counterpart in Python for "while not EOF"
问题描述
为了读取一些文本文件,在 C 或 Pascal 中,我总是使用以下片段来读取数据直到 EOF:
while not eof do begin阅读线(一);做点什么;结尾;
因此,我想知道如何在 Python 中做到这一点既简单又快速?
循环读取文件行:
使用 open('somefile') 作为 openfileobject:对于 openfileobject 中的行:做点什么()
文件对象是可迭代的,并且在 EOF 之前产生行.将文件对象用作可迭代对象使用缓冲区来确保高性能读取.
您可以对 stdin 执行相同操作(无需使用 raw_input()
:
导入系统对于 sys.stdin 中的行:做点什么()
为了完成图片,二进制读取可以完成:
from functools import partial使用 open('somefile', 'rb') 作为 openfileobject:对于 iter(partial(openfileobject.read, 1024), b'') 中的块:做点什么()
其中 chunk
一次最多包含来自文件的 1024 个字节,当 openfileobject.read(1024)
开始返回空字节字符串时,迭代停止.>
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;
Thus, I wonder how can I do this simple and fast in Python?
Loop over the file to read lines:
with open('somefile') as openfileobject:
for line in openfileobject:
do_something()
File objects are iterable and yield lines until EOF. Using the file object as an iterable uses a buffer to ensure performant reads.
You can do the same with the stdin (no need to use raw_input()
:
import sys
for line in sys.stdin:
do_something()
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), b''):
do_something()
where chunk
will contain up to 1024 bytes at a time from the file, and iteration stops when openfileobject.read(1024)
starts returning empty byte strings.
这篇关于Python 中“while not EOF"的完美对应物是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!