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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15599639/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:31:09  来源:igfitidea点击:

What is the perfect counterpart in Python for "while not EOF"

pythonfileiterationeof

提问by Allen Koo

To read some text file, in C or Pascal, I always use the following snippets to read the data until EOF:

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

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

Thus, I wonder how can I do this simple and fast in Python?

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

采纳答案by Martijn Pieters

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.

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

You can do the same with the stdin (no need to use raw_input():

您可以对 stdin 执行相同操作(无需使用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 chunkwill contain up to 1024 bytes at a time from the file, and iteration stops when openfileobject.read(1024)starts returning empty byte strings.

where 一次chunk最多包含来自文件的 1024 个字节,当openfileobject.read(1024)开始返回空字节字符串时,迭代停止。

回答by NPE

The Python idiom for opening a file and reading it line-by-line is:

打开文件并逐行读取的 Python 习惯用法是:

with open('filename') as f:
    for line in f:
        do_something(line)

The file will be automatically closed at the end of the above code (the withconstruct takes care of that).

该文件将在上述代码结束时自动关闭(with结构负责)。

Finally, it is worth noting that linewill preserve the trailing newline. This can be easily removed using:

最后,值得注意的是,line将保留尾随换行符。这可以使用以下方法轻松删除:

line = line.rstrip()

回答by dawg

You can imitate the C idiom in Python.

您可以在 Python 中模仿 C 习语。

To read a buffer up to max_sizenumber of bytes, you can do this:

要读取最多max_size字节数的缓冲区,您可以执行以下操作:

with open(filename, 'rb') as f:
    while True:
        buf = f.read(max_size)
        if not buf:
            break
        process(buf)

Or, a text file line by line:

或者,一个文本文件一行一行:

# warning -- not idiomatic Python! See below...
with open(filename, 'rb') as f:
    while True:
        line = f.readline()
        if not line:
            break
        process(line)

You need to use while True / breakconstruct since there is no eof testin Python other than the lack of bytes returned from a read.

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

In C, you might have:

在 C 中,你可能有:

while ((ch != '\n') && (ch != EOF)) {
   // read the next ch and add to a buffer
   // ..
}

However, you cannot have this in Python:

但是,您不能在 Python 中使用它:

 while (line = f.readline()):
     # syntax error

because assignments are not allowed in expressionsin Python (although recent versions of Python can mimic this using assignment expressions, see below).

因为在 Python 的表达式不允许赋值(尽管最近版本的 Python 可以使用赋值表达式来模拟这一点,见下文)。

It is certainly moreidiomatic in Python to do this:

在 Python 中这样做当然惯用:

# THIS IS IDIOMATIC Python. Do this:
with open('somefile') as f:
    for line in f:
        process(line)


Update:Since Python 3.8 you may also use assignment expressions:

更新:自 Python 3.8 起,您还可以使用赋值表达式

 while line := f.readline():
     process(line)

回答by A R

You can use below code snippet to read line by line, till end of file

您可以使用下面的代码片段逐行读取,直到文件结束

line = obj.readline()
while(line != ''):

    # Do Something

    line = obj.readline()

回答by Aditeya Pandey

You can use the following code snippet. readlines() reads in the whole file at once and splits it by line.

您可以使用以下代码片段。readlines() 一次读入整个文件并按行拆分。

line = obj.readlines()

回答by user5472996

While there are suggestions above for "doing it the python way", if one wants to really have a logic based on EOF, then I suppose using exception handling is the way to do it --

虽然上面有关于“以 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 ...

Example:

例子:

$ 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

Or press Ctrl-Zat a raw_input()prompt (Windows, Ctrl-ZLinux)

或者按Ctrl-Zraw_input()提示符(Windows,Ctrl-ZLinux的)