Python 中“while not EOF”的完美对应词是什么[重复]
- 2025-03-05 09:18:00
- admin 原创
- 59
问题描述:
要读取某些文本文件,在 C 或 Pascal 中,我总是使用以下代码片段来读取数据直到 EOF:
while not eof do begin
readline(a);
do_something;
end;
因此,我想知道如何在 Python 中简单快速地做到这一点?
解决方案 1:
循环读取文件内的行:
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()
其中chunk
每次将包含文件中最多 1024 个字节,并且当openfileobject.read(1024)
开始返回空字节字符串时迭代停止。
解决方案 2:
您可以在 Python 中模仿 C 的习语。
要读取最多(>0) 个字节的缓冲区,您可以执行以下操作:max_size
with open(filename, 'rb') as f:
while True:
buf = f.read(max_size)
if not buf :
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)
您需要使用while True / break
构造,因为除了读取返回的字节数不足之外,Python 中没有 eof 测试。
在 C 语言中,你可能有:
while ((ch != '
') && (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。
解决方案 3:
打开文件并逐行读取的 Python 习惯用法是:
with open('filename') as f:
for line in f:
do_something(line)
该文件将在上述代码结束时自动关闭(with
构造会处理该问题)。
最后,值得注意的是,这line
将保留尾随的换行符。可以使用以下方法轻松删除它:
line = line.rstrip()
解决方案 4:
您可以使用下面的代码片段逐行读取,直到文件末尾
line = obj.readline()
while(line != ''):
# Do Something
line = obj.readline()
解决方案 5:
虽然上面有“按照 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
或者Ctrl-Z
在raw_input()
提示符下按(Windows、Ctrl-Z
Linux)
解决方案 6:
除了@dawg的出色回答之外,使用海象运算符(Python> = 3.8)的等效解决方案:
with open(filename, 'rb') as f:
while buf := f.read(max_size):
process(buf)
解决方案 7:
您可以使用以下代码片段。readlines() 一次读取整个文件并按行拆分。
line = obj.readlines()
解决方案 8:
这样怎么样!简单点!
for line in open('myfile.txt', 'r'):
print(line)
无需浪费多余的行。并且无需使用with
关键字,因为当没有文件对象的引用时,文件将自动关闭。
扫码咨询,免费领取项目管理大礼包!