Python 中“while not EOF”的完美对应物是什么

新手上路,请多包涵

要读取一些文本文件,在 C 或 Pascal 中,我总是使用以下代码片段来读取数据直到 EOF:

 while not eof do begin
  readline(a);
  do_something;
end;

因此,我想知道如何在 Python 中简单快速地做到这一点?

原文由 Allen Koo 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 439
2 个回答

遍历文件以读取行:

 with open('somefile') as openfileobject:
    for line in openfileobject:
        do_something()

文件对象是可迭代的并且在 EOF 之前产生行。将文件对象用作可迭代对象使用缓冲区来确保高性能读取。

您可以对标准输入执行相同的操作(无需使用 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) 开始返回空字节字符串时迭代停止。

原文由 Martijn Pieters 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以在 Python 中模仿 C 惯用语。

读取 最多 max_size (>0) 字节数的缓冲区,您可以这样做:

 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)

您需要使用 while True / break 构造,因为除了读取返回的字节数不足之外,Python 中 没有 eof 测试

在 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,这仍然有效。

原文由 dawg 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题