如何在Python中逐行读取文件(或stdin)而不是等待读取整个文件

BiG*_*YaN 7 python filter

我们在磁盘中有几个巨大的文件(大于RAM的大小).我想在python中逐行读取它们并在终端输出结果.我已经完成了[1]和[2],但我正在寻找不等到整个文件被读入内存的方法.

我将使用这两个命令:

cat fileName | python myScript1.py
python myScript2.py fileName
Run Code Online (Sandbox Code Playgroud)

[1] 你如何从Python中读取stdin? [2] 如何在python中编写unix过滤器?

Tim*_*ker 8

这是Python 中文件对象标准行为:

with open("myfile.txt", "r") as myfile:
    for line in myfile:
        # do something with the current line
Run Code Online (Sandbox Code Playgroud)

要么

for line in sys.stdin:
    # do something with the current line
Run Code Online (Sandbox Code Playgroud)