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

muk1a3rh  于 2023-02-07  发布在  Python
关注(0)|答案(3)|浏览(136)
    • 此问题在此处已有答案**:

How should I read a file line-by-line in Python?(3个答案)
(9个答案)
How do I read from stdin?(24个答案)
15小时前关门了。
我想在python中逐行读取和处理一些大文件,并在终端中输出结果,我已经尝试过How do I read from stdin?How do I write a unix filter in python?,但我正在寻找不需要等到整个文件被读入内存的方法。
我将使用以下两个命令:

cat fileName | python myScript1.py
python myScript2.py fileName
g6baxovj

g6baxovj1#

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

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

for line in sys.stdin:
    # do something with the current line
fnx2tebb

fnx2tebb2#

只需遍历文件:

with open('huge.file') as hf:
  for line in hf:
    if 'important' in line:
      print(line)

这将需要O(1)内存。
要从stdin读取,只需迭代sys.stdin而不是hf

import sys
for line in sys.stdin:
  if 'important' in line:
    print(line)
cgyqldqp

cgyqldqp3#

if __name__ == '__main__':
    while 1:
        try:
            a=raw_input()
        except EOFError:
            break
        print a

这将从stdin读取到EOF。要使用第二种方法读取文件,可以使用Tim的方法

with open("myfile.txt", "r") as myfile:
    for line in myfile:
        print line
        # do something with the current line

相关问题