【问题标题】:Go back to a specific line when reading a file in a loop循环读取文件时返回特定行
【发布时间】:2020-02-10 15:46:53
【问题描述】:

我正在循环读取一个非常大的 txt 文件。 迭代特定行时,存在条件,根据满足哪些条件,我想返回并从另一个起始行号再次开始迭代文件。

例如:

with open(filename) as f:
    for inputline in f:
        if inputline.strip() == 'abc':
            #goto line 3 and start the loop again
        print(inputline.strip())

假设输入文件是:

1
2
3
4
5
abc
6
7

输出应该是:

1
2
3
4
5
3
4
5
3
4
5.....

我知道这个输入最终会进入一个无限循环并且永远不会终止。但我仍然想知道如何使用简单的 readline 来实现这一点。由于每行的长度不统一,我无法使用 seek 命令。

【问题讨论】:

  • 你不能回去 - 你宁愿在内存中记住以前的行或在行中计算字符以保留可以与 seek() 一起使用的行的位置
  • “从另一个起始行号再次迭代文件”,当你说这总是一个特定的行还是会改变?
  • @nithin11 - 行会根据某些条件而变化。
  • @user2778822 因此对于 thisinputline.strip() == 'abc' 条件,它进入第 3 行,而对于其他一些条件,它进入其他行。是这样的吗?
  • @nithin11 是的,没错

标签: python python-3.x readline readlines


【解决方案1】:

您可以使用 recursive 函数结合枚举来做到这一点:

def fn(lines, index=0):
    for i, line in enumerate(lines, start=index):
    if line.strip() == 'abc':
        fn(lines, i)
    else:
        print(line)

with open(filename) as f:
    fn(f.readlines())

【讨论】:

    【解决方案2】:

    可以通过调用文件对象的tell方法,使用列表来跟踪每一行的结束位置(也是下一行的开始位置),然后使用seek方法将文件指针重新定位到上一行的位置:

    with open(filename) as f:
        positions = []
        for inputline in f:
            position = f.tell()
            if not positions or position > positions[-1]:
                positions.append(position)
            inputline = inputline.strip()
            if inputline == 'abc':
                # the starting position of line number 3 is the ending position of line number 2
                f.seek(positions[1])
            else:
                print(inputline)
    

    【讨论】:

      【解决方案3】:

      你可以使用file.seek():

      with open(filename) as f:
          while f.readable():
              inputline = next(f)
              if inputline.strip() == 'abc':
                  f.seek(3)
                  next(f)
              else:
                  print(inputline.strip())
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-03-04
        • 1970-01-01
        • 2015-05-02
        • 1970-01-01
        • 2012-01-24
        相关资源
        最近更新 更多