22

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?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Ben Cartwright
  • 233
  • 1
  • 2
  • 5
  • 3
    what have you tried ? Could you show us some code ? What's the exact problem ? – pypat Jun 10 '13 at 10:35
  • 2
    How can we show you how to fix it if you don't show us your code? – John La Rooy Jun 10 '13 at 10:36
  • Move the cursor to the beginning of the file- fp.seek(0) and then fp.read() – N Randhawa Aug 27 '16 at 13:21
  • 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 Jan 21 '19 at 19:15

2 Answers2

42

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)
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
  • I think it is still better to keep the file opened and re-read it, open and close operations are very costly. You took a workaround by adding a sleep call. – Ahmed Hamdy Aug 02 '18 at 18:16
  • @AhmedHamdy, Leaving files open also has a cost. It's not so much a problem now days, but it used to be easy to run out of file descriptors if you were opening a lot of files. It's a balance you need to manage depending on the situation. – John La Rooy Aug 03 '18 at 00:04
20

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

file.seek(0)

Then you can successfully read it.

Konstantin Dinev
  • 34,219
  • 14
  • 75
  • 100