如何在线读取文件并返回特定行以再次读取

How to read file in line and back to specific line to read it again

我正在尝试在文件中查找特定字符串(假设这是条件 1.1),如果找到该字符串,我需要在条件 1.1 字符串之后找到另一个字符串(假设这是条件 1.2) .如果条件 1.2 存在,我需要回到条件 1.1 加一行。并从那里再次读取线,以防我找到条件字符串 2.1 , 3.1, 4.1.

假设文件是​​这样的

line 1
line 2
condition 1.1
line 4
line 5
line 6
line 7
condition 2.1
line 9
line 10
line 11
condition 2.2
line 12
line 13
condition 1.2

到目前为止,我所做的是使用 f.readline 和条件 1.1 和 1.2 检查读取文件行,而不考虑检查条件 2.1 和 2.2。

如何实现这样的场景?我考虑过类似 DFS 的东西,但我认为 python 文件打开没有 readline before 功能

这是我的伪代码

def beta(f, line):
    if("STRING A Condition 1.1" in line):
        while True:
            if("STRING B Condition 1.2" in line):
                return 1
            if(line is none):
                return None
            line = f.readline() # This is my code problem. it continues the f.readline of the caller.

def alpha():
    with open(file_name, 'r') as f:
        line = f.readline()
        while line:
            value = beta(f, line)
            if(value is not None):
                print("dummy yes")
            line = f.readline()
            if(line is None):
                break

考虑使用 seek and tell 来保存和恢复您在文件中的位置。

f.seek(x, y) 将文件 f 中的当前位置移动到与 y.

偏移 x 的位置

f.tell() returns 当前在文件中的位置 f.

例如,考虑以下代码:

with open("test.txt") as f:
    saved_place = 0
    line = f.readline()
    while line:
        if "condition 1.1" in line:
            # save your place in the file
            saved_place = f.tell()
            while line:
                if "condition 1.2" in line:
                    # 'rewind' the file
                    f.seek(saved_place, 0)
                    print(f.read())
                line = f.readline()
        line = f.readline()

当你遇到条件1.1时,你可以使用saved_place = f.tell()保存文件中的那个地方,然后使用f.seek(saved_place, 0)将文件中的当前位置恢复到这个地方。上面的例子简单地打印了从 1.1 之后到最后的文件,但是你可以用你喜欢的任何逻辑替换它。