Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiently finding the last line in a text file [duplicate]

Tags:

python

text

I need to extract the last line from a number of very large (several hundred megabyte) text files to get certain data. Currently, I am using python to cycle through all the lines until the file is empty and then I process the last line returned, but I am certain there is a more efficient way to do this.

What is the best way to retrieve just the last line of a text file using python?

like image 705
TimothyAWiseman Avatar asked Aug 23 '11 20:08

TimothyAWiseman


People also ask

How do you read the last line of a text file in C++?

Use seekg to jump to the end of the file, then read back until you find the first newline.

How do I display the last line of a text file?

Use the tail command to write the file specified by the File parameter to standard output beginning at a specified point. This displays the last 10 lines of the accounts file. The tail command continues to display lines as they are added to the accounts file.


2 Answers

Not the straight forward way, but probably much faster than a simple Python implementation:

line = subprocess.check_output(['tail', '-1', filename]) 
like image 167
sth Avatar answered Sep 22 '22 19:09

sth


with open('output.txt', 'r') as f:     lines = f.read().splitlines()     last_line = lines[-1]     print last_line 
like image 28
mick barry Avatar answered Sep 20 '22 19:09

mick barry