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
Read Last Line of File With the readlines() Function in Python. The file. readlines() function reads all the lines of a file and returns them in the form of a list. We can then get the last line of the file by referencing the last index of the list using -1 as an index.
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.
Use readlines() to Read the range of line from the File You can use an index number as a line number to extract a set of lines from it. This is the most straightforward way to read a specific line from a file in Python. We read the entire file using this way and then pick specific lines from it as per our requirement.
with open("file.txt") as file:
lines = file.readlines()
print(lines[-1])
with open("file.txt") as file:
for line in file:
pass
print(line)
import os
with open("file.txt", "rb") as file:
# Go to the end of the file before the last break-line
file.seek(-2, os.SEEK_END)
# Keep reading backward until you find the next break-line
while file.read(1) != b'\n':
file.seek(-2, os.SEEK_CUR)
print(file.readline().decode())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With