0

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?

The code used for writing to the file is:

import time
a= open('c:/test/aisha.txt','w')
while(1):
     a.write(str(i))
     a.write("\n")
     i+=1
a.close      
lig
  • 3,567
  • 1
  • 24
  • 36

1 Answers1

0

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.

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

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.

Gene Olson
  • 890
  • 6
  • 4