Patrick
Patrick

Reputation: 2544

Use file object of "with" more than 1 time

I want to search a particular string in file and based on that i have to process file data.

I know how to do it by opening file 2 times.

Can this be done by opening file for only 1 time ?

code:

with open(path, "r") as _file:
    for line in _file:
        if "my_string" in line:
            flag = True
            break

with open(path, "r") as _file:
    for line in _file;
        if flag:
            process line
            ...
        else:
            process differently
            ...

I tried:

with open(path, "r") as _file:
    for line in _file:
        if "my_string" in line:
            flag = True
            break

    for line in _file;
        if flag:
            process line
            ...
        else:
            process differently
            ...         

But here 2nd for loop starts from where 1st loop has left, it doesn't start from 1st line of file and that's why its not working here.

Upvotes: 1

Views: 28

Answers (1)

wRAR
wRAR

Reputation: 25559

You need to rewind the file position to the beginning before the second loop. You can do this with _file.seek(0).

Upvotes: 2

Related Questions