提问人:Allen Koo 提问时间:3/24/2013 最后编辑:cs95Allen Koo 更新时间:10/8/2022 访问量:444698
Python 中“while not EOF”的完美对应物是什么 [duplicate]
What is the perfect counterpart in Python for "while not EOF" [duplicate]
问:
要读取一些文本文件,在 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()
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()
where 一次最多包含文件中的 1024 个字节,当开始返回空字节字符串时,迭代停止。chunk
openfileobject.read(1024)
评论
line
stdin
打开文件并逐行读取的 Python 习惯用法是:
with open('filename') as f:
for line in f:
do_something(line)
该文件将在上述代码的末尾自动关闭(构造负责)。with
最后,值得注意的是,这将保留尾随换行符。这可以通过以下方法轻松删除:line
line = line.rstrip()
评论
for line in f.readlines(): ...
您可以在 Python 中模仿 C 习语。
要读取最多 (>0) 个字节数的缓冲区,可以执行以下操作:max_size
with open(filename, 'rb') as f:
while True:
buf = f.read(max_size)
if buf == 0:
break
process(buf)
或者,逐行查看文本文件:
# warning -- not idiomatic Python! See below...
with open(filename, 'rb') as f:
while True:
line = f.readline()
if not line:
break
process(line)
您需要使用构造,因为 Python 中没有 eof 测试,除了缺少从读取返回的字节之外。while True / break
在 C 语言中,您可能具有:
while ((ch != '\n') && (ch != EOF)) {
// read the next ch and add to a buffer
// ..
}
但是,您不能在 Python 中使用此功能:
while (line = f.readline()):
# syntax error
因为 Python 中的表达式中不允许赋值(尽管最新版本的 Python 可以使用赋值表达式来模拟这一点,请参见下文)。
在 Python 中,这样做当然更习惯:
# THIS IS IDIOMATIC Python. Do this:
with open('somefile') as f:
for line in f:
process(line)
更新:从 Python 3.8 开始,您还可以使用赋值表达式:
while line := f.readline():
process(line)
即使读取的行为空并持续到 EOF,这也有效。
评论
readline()
UnicodeDecodeError
for
.read
read
None
0
您可以使用下面的代码片段逐行阅读,直到文件末尾
line = obj.readline()
while(line != ''):
# Do Something
line = obj.readline()
评论
您可以使用以下代码片段。readlines() 一次读取整个文件并按行拆分。
line = obj.readlines()
虽然上面有关于“以 python 方式做”的建议,但如果真的想有一个基于 EOF 的逻辑,那么我想使用异常处理是做到这一点的方法——
try:
line = raw_input()
... whatever needs to be done incase of no EOF ...
except EOFError:
... whatever needs to be done incase of EOF ...
例:
$ echo test | python -c "while True: print raw_input()"
test
Traceback (most recent call last):
File "<string>", line 1, in <module>
EOFError: EOF when reading a line
或按提示符(Windows、Linux)Ctrl-Zraw_input()
Ctrl-Z
除了 @dawg 的精彩回答之外,使用 walrus 运算符 (Python >= 3.8) 的等效解决方案:
with open(filename, 'rb') as f:
while buf := f.read(max_size):
process(buf)
这个怎么样!让一切变得简单!
for line in open('myfile.txt', 'r'):
print(line)
无需浪费额外的线路。并且无需使用关键字,因为当没有文件对象的引用时,文件将自动关闭。with
评论
with
评论