Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print Last Line of File Read In with Python

Tags:

python

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
like image 355
pHorseSpec Avatar asked May 14 '16 14:05

pHorseSpec


People also ask

How do I print the last line of a text file in Python?

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.

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.

How do you read a single line from a file in Python?

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.


1 Answers

Three ways to read the last line of a file:

  • For a small file, read the entire file into memory

with open("file.txt") as file:            
    lines = file.readlines()
print(lines[-1])
  • For a big file, read line by line and print the last line

with open("file.txt") as file:
    for line in file:
        pass
print(line)
  • For efficient approach, go directly to the last 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())
like image 190
kafran Avatar answered Oct 14 '22 19:10

kafran