python3 file.readline EOF?

noo*_*392 5 file python-3.x

我无法确定何时使用 file.readline 到达 python 中的文件末尾

fi = open('myfile.txt', 'r')
line = fi.readline()
if line == EOF:  //or something similar
    dosomething()
Run Code Online (Sandbox Code Playgroud)

c = fp.read() if c is None: 将不起作用,因为那样我将丢失下一行的数据,如果一行只有回车,我将错过一个空行。

我看了几十个或相关的帖子,它们都只是使用了固有的循环,当它们完成时就会中断。我没有循环,所以这对我不起作用。此外,我在 GB 中有 100 行的文件大小。一个脚本可能会花费数天时间来处理一个文件。所以我需要知道如何判断我何时在 python3 中的文件末尾。任何帮助表示赞赏。谢谢!

kab*_*nus 5

我遇到了同样的问题。我的具体问题是迭代两个文件,其中较短的文件只应该在较长文件的特定读取中读取一行。

正如一些人在这里提到的,逐行迭代的自然 Pythonic 方法是,好吧,只是迭代。我坚持这种“自然性”的解决方案是手动使用文件的迭代器属性。像这样的东西:

with open('myfile') as lines:
    try:
        while True:                 #Just to fake a lot of readlines and hit the end
            current = next(lines)
    except StopIteration:
        print('EOF!')
Run Code Online (Sandbox Code Playgroud)

你当然可以用你自己的 IOWrapper 类来修饰它,但这对我来说已经足够了。只需将所有调用替换为readline对调用的调用next,并且不要忘记捕获StopIteration.


Inf*_*ity 0

with open(FILE_PATH, 'r') as fi:
    for line in iter(fi.readline, ''):
        parse(line)
Run Code Online (Sandbox Code Playgroud)