Python 多个换行的文件 readline 问题

Python file readline issue with multiple linefeed

我正在尝试逐行解析一个大文件。但是,当我 运行 这个程序时 :

def main():
    fd_in = open('file1.txt')
    ctr = 0

    while True:
        line = fd_in.readline().strip()
        if not line:
            break

        print(line)

        ctr += 1
        if ctr % 1000000 == 0:
            print(ctr)

    print(fd_in.tell())
    fd_in.close()

它在读取所有文件之前停止。

[...]
495448578 # tell result

如果我在错误的文件结尾之前对 8 个字节进行 hexdump,我会得到:

hexdump -C -s 495448570 -n 10 file1.txt
1d87f1fa  68 65 6c 6c 6f 0d 0a 0d 0a 68                    |hello....h|

所以 readline 应该 return 换行而不是空字符串。

我是不是漏掉了什么?

感谢您的帮助。

如果您的 line 只是空格,strip() 会将 line 变成空字符串,从而触发 break。检查 eof 后剥离。

def main():
    fd_in = open('file1.txt')
    ctr = 0

    while True:
        line = fd_in.readline()
        if not line:
            break
        line = line.strip()

        print(line)

        ctr += 1
        if ctr % 1000000 == 0:
            print(ctr)

    print(fd_in.tell())
    fd_in.close()