Skip to content Skip to sidebar Skip to footer

Print Last Line Of File Read In With 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

Solution 1:

One option is to use file.readlines():

f1 = open(inputFile, "r")
last_line = f1.readlines()[-1]
f1.close()

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:

withopen(inputFile, "r") as f1:
    last_line = f1.readlines()[-1]

Solution 2:

Do you need to be efficient by not reading all the lines into memory at once? Instead you can iterate over the file object.

withopen(inputfile, "r") as f:
    for line in f: passprint line #this is the last line of the file

Solution 3:

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:

fi=open(inputFile, 'r')
lastline = ""for line infi:
  lastline = line
print lastline

Solution 4:

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.

import csv

lis = list(csv.reader(open(inputFile)))
print lis[-1] # prints final line as a list of strings

Solution 5:

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

withopen("file.txt") as file:
    for line in file:
        passprint(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 nextbreak-line
    while file.read(1) != b'\n':
        file.seek(-2, os.SEEK_CUR) 
    print(file.readline().decode())

Post a Comment for "Print Last Line Of File Read In With Python"