Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-read an open file Python

Tags:

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?

like image 352
Ben Cartwright Avatar asked Jun 10 '13 10:06

Ben Cartwright


People also ask

Can you open a file twice in Python?

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.

How do you reset a text file in Python?

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.

How do I reset a pointer in Python?

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).


2 Answers

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) 
like image 111
John La Rooy Avatar answered Oct 04 '22 03:10

John La Rooy


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

file.seek(0) 

Then you can successfully read it.

like image 30
Konstantin Dinev Avatar answered Oct 04 '22 03:10

Konstantin Dinev