- 此问题在此处已有答案**:
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
3条答案
按热度按时间g6baxovj1#
这是Python中文件对象的标准行为:
或
fnx2tebb2#
只需遍历文件:
这将需要O(1)内存。
要从stdin读取,只需迭代
sys.stdin
而不是hf
:cgyqldqp3#
这将从stdin读取到EOF。要使用第二种方法读取文件,可以使用Tim的方法
即