Read the last line of the file

Imagine I have a file with

Xpto, 50.30.60 Xpto, a, V, C Xpto, 1.9.0 Xpto, 30.30.60

that a txt file can be added many times, and when I open the file, I only want to get the values ​​of the last line of the txt file ... How can I do this in python? reading the last line?

thanks

+3
source share
4 answers

I think my answer from the last time it came to mind was missed. :-)

If you are in a unix box, os.popen("tail -10 " + filepath).readlines() will probably be the fastest way. Otherwise, it depends on how reliable you are. The methods proposed so far all fall, one way or another. For reliability and speed, in most cases the usual case is that you probably want something like a logarithmic search: use file.seek to go to the end of the file minus 1000 characters, read it, check how many lines it contains, then to EOF minus 3000 characters, read 2000 characters, count lines, then EOF minus 7000, read 4000 characters, count lines, etc. until you have as many lines as you need. But if you know for sure that it will always run in files with a reasonable line length, you may not need to.

You can also find inspiration in the source code for unix tail .

+10
source

f.seek( pos ,2) searches for "pos" relative to the end of the file. try a reasonable value for pos, then readlines () and get the last line.

You should consider when "pos" is not a good guess, i.e. Suppose you select 300, but the last line is 600 characters! in this case, try again with a reasonable guess until you capture the entire line. (this worst case should be very rare)

+1
source

Why not just look for the end of the file and read until you click on a new line?

 i=0 while(1): f.seek(i, 2) c = f.read(1) if(c=='\n'): break 
0
source

Not sure about the specific python-based implementation, but in a more aggressive language, what you would like to do is skip (search) to the end of the file, and then read each character in the reverse order until you reach the line that your file uses, usually a character with a value of 13. just read forward from this point to the end of the file and you will have the last line in the file.

-one
source

All Articles