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:
Can anyone suggest a way to get Python to re-read the file?
The same file can be opened more than once in the same program (or in different programs). Each instance of the open file has its own file pointer that can be manipulated independently. In python each time you call open() it creates a new file object(iterator), so you're safe.
Clear a Text File Using the open() Function in write Mode Opening a file in write mode clears its data. Also, if the file specified doesn't exist, Python will create a new one. The simplest way to delete a file is to use open() and assign it to a new variable in write mode.
You can use the seek(offset[, whence]) method. It sets the file's current position, like stdio's fseek(). The whence argument is optional and defaults to 0 (absolute file positioning); other values are 1 (seek relative to the current position) and 2 (seek relative to the file's end).
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)
You can move the cursor to the beginning of the file the following way:
file.seek(0)
Then you can successfully read it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With