在循环中读取文件时返回到特定行

2024-04-26 06:54:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在一个很大的循环中读取一个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命令,因为每行的长度不一致。你知道吗


Tags: 文件intxtforifaswithopen
3条回答

您可以使用recursive函数和enumerate来实现这一点:

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())

您可以使用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())

通过调用file对象的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)

相关问题 更多 >