Skip to content
Advertisement

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

I am trying to find a specific string in a file(let’s say this is condition 1.1) and if that string was found, I need to find another string right after condition 1.1 string (let’s say this is condition 1.2). if condition 1.2 exist, I need to get back to condition 1.1 plus one line. and readline again from there in case I found string of condition 2.1 , 3.1, 4.1.

Let’s say the file is something like this

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

what I’ve done so far are reading the file line using f.readline with condition 1.1 and 1.2 check without thinking about checking condition 2.1 and 2.2.

How to acheive this such scenario? I’ve thought about something like DFS but I dont think python file open has readline before functionalities

Here is my pseudocode

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

Advertisement

Answer

Consider using seek and tell to save and restore your place in the file.

f.seek(x, y) moves the current position in file f to a position that is offset by x from y.

f.tell() returns the current position in the file f.

For example, consider the following code:

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

When you encounter condition 1.1, you can save that place in the file using saved_place = f.tell(), and later, restore the current position in the file to this place using f.seek(saved_place, 0). The example above simply prints the file from just after 1.1 to the end, but you can replace it with whatever logic you like.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement