Python中"完全没有EOF"的完美对应点是什么?

All*_*Koo 104 python iteration file eof

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

while not eof do begin
  readline(a);
  do_something;
end;
Run Code Online (Sandbox Code Playgroud)

因此,我想知道如何在Python中简单快速地完成这项工作?

Mar*_*ers 176

循环遍历文件以读取行:

with open('somefile') as openfileobject:
    for line in openfileobject:
        do_something()
Run Code Online (Sandbox Code Playgroud)

文件对象是可迭代的,并产生直到EOF的行.将文件对象用作iterable使用缓冲区来确保执行读取.

你可以用stdin做同样的事情(不需要使用raw_input():

import sys

for line in sys.stdin:
    do_something()
Run Code Online (Sandbox Code Playgroud)

要完成图片,二进制读取可以通过以下方式完成:

from functools import partial

with open('somefile', 'rb') as openfileobject:
    for chunk in iter(partial(openfileobject.read, 1024), b''):
        do_something()
Run Code Online (Sandbox Code Playgroud)

其中一次chunk最多包含1024个字节,并且在openfileobject.read(1024)开始返回空字节字符串时迭代停止.

  • 注意:line的末尾会有一个换行符。 (2认同)

daw*_*awg 55

你可以用Python模仿C语言.

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

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

或者,逐行文本文件:

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

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

在C中,您可能有:

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

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

 while (line = f.readline()):
     # syntax error
Run Code Online (Sandbox Code Playgroud)

因为Python 中的表达式不允许赋值.

在Python中,这当然是惯用的:

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

  • 作为C和Perl程序员,您的观点是**[表达式中不允许赋值](http://docs.python.org/2/faq/design.html#why-can-ti-use-an-assignment -in-an-expression)**对我来说至关重要. (3认同)
  • 当每次迭代需要对多个输入行进行操作时,“while True:”方法也很有用,而惯用的 Python 不允许这样做(据我所知,无论如何)。 (2认同)

NPE*_*NPE 18

用于打开文件并逐行读取的Python习语是:

with open('filename') as f:
    for line in f:
        do_something(line)
Run Code Online (Sandbox Code Playgroud)

该文件将在上述代码的末尾自动关闭(with构造处理该文件).

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

line = line.rstrip()
Run Code Online (Sandbox Code Playgroud)


A R*_*A R 11

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

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

    # Do Something

    line = obj.readline()
Run Code Online (Sandbox Code Playgroud)


小智 11

虽然上面有"做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 ...
Run Code Online (Sandbox Code Playgroud)

例:

$ 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
Run Code Online (Sandbox Code Playgroud)

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