19
votes

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?

2
what have you tried ? Could you show us some code ? What's the exact problem ? - pypat
How can we show you how to fix it if you don't show us your code? - John La Rooy
Move the cursor to the beginning of the file- fp.seek(0) and then fp.read() - N Randhawa
The answers don't mention it explicitly, but when you read a file, the file object's position moves to the end of the file. The position is automatically reset when you open the file again, or you can manually set it with f.seek. - wjandrea

2 Answers

36
votes

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)
19
votes

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

file.seek(0)

Then you can successfully read it.