Re-read an open file Python

I have a script that reads a file and then completes tests based on that file however I am running into a problem because the file reloads after one hour and I cannot get the script to re-read the file after or at that point in time.

So:

  • GETS NEW FILE TO READ
  • Reads file
  • performs tests on file
  • GET NEW FILE TO READ (with same name – but that can change if it is part of a solution)
  • Reads new file
  • perform same tests on new file

Can anyone suggest a way to get Python to re-read the file?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Either seek to the beginning of the file

with open(...) as fin:
    fin.read()   # read first time
    fin.seek(0)  # offset of 0
    fin.read()   # read again

or open the file again (I’d prefer this way since you are otherwise keeping the file open for an hour doing nothing between passes)

with open(...) as fin:
    fin.read()   # read first time

with open(...) as fin:
    fin.read()   # read again

Putting this together

while True:
    with open(...) as fin:
        for line in fin:
            # do something 
    time.sleep(3600)

Method 2

You can move the cursor to the beginning of the file the following way:

file.seek(0)

Then you can successfully read it.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x