【问题标题】:How to read a file (or stdin) line by line in Python not waiting for reading entire file如何在 Python 中逐行读取文件(或标准输入)而不是等待读取整个文件
【发布时间】:2023-03-20 23:18:01
【问题描述】:

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

我会使用这两个命令:

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

[1]How do you read from stdin in Python? [2]How do I write a unix filter in python?

【问题讨论】:

    标签: python filter


    【解决方案1】:

    这是 Python 中的standard behavior of file objects:

    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
    

    【讨论】:

      【解决方案2】:

      只需遍历file:

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

      这将需要 O(1) 内存。

      要从标准输入读取,只需迭代 sys.stdin 而不是 hf:

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

      【讨论】:

      • 我是一个 python 新手,你能解释一下“简单地迭代 sys.stdin 而不是 hf”。你是说for line in sys.stdin 吗?
      • 是的,sys.stdin 只是一个 file object,其行为类似于您手动打开的文件。
      【解决方案3】:
      if __name__ == '__main__':
          while 1:
              try:
                  a=raw_input()
              except EOFError:
                  break
              print a
      

      这将从标准输入读取直到 EOF。 使用第二种方法读取文件,可以使用Tim的方法

      即

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

      【讨论】:

      • 感谢这两种方法:)
      • 这种从标准输入读取的方法极其繁琐。 sys.stdin 是类文件对象,可以替代使用。
      猜你喜欢
      • 1970-01-01
      • 2012-10-13
      • 1970-01-01
      • 2013-12-17
      • 2011-03-30
      • 2011-10-22
      • 2011-06-02
      • 1970-01-01
      相关资源
      最近更新 更多