To read the last line of a file in Python, the easiest way is with the Python file readlines() function.
with open("example.txt") as f:
last_line = f.readlines()[-1]
One other way you can read the last line of a file is with the read() function and then split it on the new line character.
with open("example.txt") as f:
lines = f.read()
last_line = lines.split("/n")[-1]
One last way you can get the last line of a file is with a for loop which loops through the lines of the file until the end.
with open("example.txt") as f:
for line in f:
pass
last_line = line
When working with files, the ability to easily read from or write to a file is valuable.
One such case is if you want to just read the last line of a file.
There are a number of different ways you can read the last line from a file in Python.
The easiest way, in our opinion, is with the file readlines() function. readlines() reads all of the lines and returns a list.
After using readlines(), you can get the last element of the list, which will be the last line of the file.
Below is an example showing how you can get the last line of a file using readlines() in Python.
with open("example.txt") as f:
last_line = f.readlines()[-1]
Using read() and split() in Python to Read Last Line of File
Another way you can read the last line of a file is with the read() function.
read() reads the entire file you are working with.
After reading the entire file with read(), you can use split() to split the file by the newline character and get the lines.
After this, you have a list with the lines of the file and you can again access the last element of the list of lines.
Below is an example showing how you can get the last line of a file using read() and split() in Python.
with open("example.txt") as f:
lines = f.read()
last_line = lines.split("/n")[-1]
Using For Loop to Get Last Line of File
One last way you can get the last line of a file is with a for loop.
We can loop over the lines in a file and then after the loop has completed, you can get the last line of the file.
Below is an example showing how you can get the last line of a file using a for loop in Python.
with open("example.txt") as f:
for line in f:
pass
last_line = line
Hopefully this article has been useful for you to learn how to read the last line from a file in your Python programs.