Accessing the most recent line in a continuously updating file using python
<p>I am reading data from a file 'aisha.txt'. The data is read line by line and the file is continuously updating and now I want to access the most recent line or end of file. How can I do that?</p>

<p>The code used for writing to the file is: </p>

<pre><code>import time
a= open('c:/test/aisha.txt','w')
while(1):
     a.write(str(i))
     a.write("\n")
     i+=1
a.close      
</code></pre>

<p>To read the last line in a file, it is easiest if you know the maximum length of any line in the file.  Then you can seek back that number of characters from the end of the file and read forward.   The last line you read before end of file is the one you want.</p>

<pre><code>import os

MAXLEN = 132

file = open('testfile','r')

try:
    file.seek(-MAXLEN, os.SEEK_END)
except IOError:
    pass

last = "No lines in file"
while True:
    s = file.readline()
    if len(s) == 0:
        break
    last = s

file.close()

print last
</code></pre>

<p>Note that if you are running this program on Windows, and the original file is still open, the program will fail because on Windows a file opened for write is not readable until it is closed.</p>

python file