How could I print
the final line of a text file read in with python?
fi=open(inputFile,"r")
for line in fi:
#go to last line and print it
How could I print
the final line of a text file read in with python?
fi=open(inputFile,"r")
for line in fi:
#go to last line and print it
If you care about memory this should help you.
If you can afford to read the entire file in memory(if the filesize is considerably less than the total memory), you can use the readlines() method as mentioned in one of the other answers, but if the filesize is large, the best way to do it is:
You could use
csv.reader()
to read your file as a list and print the last line.Cons: This method allocates a new variable (not an ideal memory-saver for very large files).
Pros: List lookups take O(1) time, and you can easily manipulate a list if you happen to want to modify your inputFile, as well as read the final line.
This might help you.
Do you need to be efficient by not reading all the lines into memory at once? Instead you can iterate over the file object.
One option is to use
file.readlines()
:If you don't need the file after, though, it is recommended to use contexts using
with
, so that the file is automatically closed after: