0

Consider the following Python script :

import time

f = open('data.txt')
while True :
    line = next(f)
    if line : print(line)
    time.sleep(1)

Now assume that when this code starts executing, data.txt contains only 5 physical lines. But this file data.txt is getting appended with more lines dynamically.

Is there some way that I can read the new lines that are getting appended to data.txt.

My observation is that the text read is the text existing in data.txt at the time open is performed.

user3282758
  • 1,379
  • 11
  • 29
  • 1
    https://stackoverflow.com/questions/12523044/how-can-i-tail-a-log-file-in-python#12523371 – AkshayDandekar Feb 05 '21 at 15:23
  • Check out `seek` method: https://python-reference.readthedocs.io/en/latest/docs/file/seek.html – Andrew Allaire Feb 05 '21 at 15:23
  • seek method will not work unless you close the file handle and open it again. – lllrnr101 Feb 05 '21 at 15:30
  • @ lllrnr101 is it that when a file is opened a copy of this file is created for the reader process? – user3282758 Feb 05 '21 at 15:41
  • @Illmr101 Not sure why one would have to close the file handle. Just tried using opening a file in "a+" mode and using seek, write, and read together and it seems to work fine. Although I am not sure about mixing it with print rather than write. – Andrew Allaire Feb 05 '21 at 15:47
  • @user3282758 Whether a copy is created or not depends on your OS, although most modern OS use some form of caching to improve read/write performance. – user79161 Feb 05 '21 at 15:51
  • @Andrew Allaire if the same process opens in a+ mode and does read and write with a proper flush, it works. But I am talking about one process reading and the other parallelly modifying (say getting modified by an editor). In this case it does not work – user3282758 Feb 05 '21 at 18:34

0 Answers0