【问题标题】:Read file until specific line in python读取文件直到python中的特定行
【发布时间】:2015-01-23 23:24:13
【问题描述】:

我有一个文本文件。我正在使用正则表达式解析一些数据。所以打开文件并阅读它并解析它。但我不想在该文本文件中的某些特定行之后读取和解析数据。例如

file start here..
some data...
SPECIFIC LINE
some data....

现在我不想在 SPECIFIC LINE 之后读取文件... 当那条线到达时,有什么方法可以停止阅读?

【问题讨论】:

  • 是的,但是在那之后您将如何处理该文件?
  • 带有breakfor 循环?这是相当标准的......你能告诉我们你的努力,以便我们可以帮助你,而不是仅仅要求我们为你做这件事吗?

标签: python regex python-2.7 file file-read


【解决方案1】:

只读取第一行 n,而不加载整个文件:

n = 5
with open(r'C:\Temp\test.txt', encoding='utf8') as f:
    head = [next(f) for x in range(n)]

【讨论】:

    【解决方案2】:

    使用iter()sentinel参数:

    with open('test.txt') as f:
        for line in iter(lambda: f.readline().rstrip(), 'SPECIFIC LINE'):
            print(line)
    

    输出:

    file start here..
    some data...
    

    参考:https://docs.python.org/2/library/functions.html#iter

    【讨论】:

      【解决方案3】:

      这很简单,您可以使用break 语句提前终止循环。

      filename = 'somefile.txt'
      
      with open(filename, 'r') as input:
         for line in input:
             if 'indicator' in line:
                  break
      

      使用with 创建一个复合语句,确保在进入和离开with 语句的范围时分别调用__enter__()__exit__()。出于文件读取的目的,这将防止任何悬空的文件句柄。

      break 语句告诉循环立即终止。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-28
        • 2020-08-15
        • 1970-01-01
        • 2015-09-06
        • 2018-07-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多