13

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
pHorseSpec
  • 1,246
  • 5
  • 19
  • 48

8 Answers8

19

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:

with open(inputFile, "r") as f1:
    last_line = f1.readlines()[-1]
Rushy Panchal
  • 16,979
  • 16
  • 61
  • 94
  • 9
    This should not be used for large files since it reads them in completely, and only throws away all but the last line afterwards. – Elmar Peise Mar 30 '17 at 13:34
11

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

with open(inputfile, "r") as f:
    for line in f: pass
    print line #this is the last line of the file
gnicholas
  • 2,041
  • 1
  • 21
  • 32
  • The files being read in are small for me, so efficiency isn't greatly important, but this will definitely be useful for scripts with larger files. – pHorseSpec May 14 '16 at 14:55
  • the smartest solution, you are going to loop in the file in any case. – Florjan Feb 08 '23 at 10:11
7

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())
kafran
  • 729
  • 7
  • 13
  • what is the time gain of method 3 `file.seek(-2, os.SEEK_END)` over methods 1 and 2 which use in this answer ? – D.L Dec 04 '22 at 12:20
4

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 in fi:
  lastline = line
print lastline
ajays20078
  • 368
  • 1
  • 3
  • 10
  • 1
    Your assignment `lastline = line` is not really necessary and therefore inefficient. You should replace it with a simple `pass` statement. – winklerrr Oct 13 '17 at 12:26
2

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
Daniel
  • 2,345
  • 4
  • 19
  • 36
1

If you care about memory this should help you.

last_line = ''
with open(inputfile, "r") as f:
    f.seek(-2, os.SEEK_END)  # -2 because last character is likely \n
    cur_char = f.read(1)

    while cur_char != '\n':
        last_line = cur_char + last_line
        f.seek(-2, os.SEEK_CUR)
        cur_char = f.read(1)

    print last_line
0

This might help you.

class FileRead(object):

    def __init__(self, file_to_read=None,file_open_mode=None,stream_size=100):

        super(FileRead, self).__init__()
        self.file_to_read = file_to_read
        self.file_to_write='test.txt'
        self.file_mode=file_open_mode
        self.stream_size=stream_size


    def file_read(self):
        try:
            with open(self.file_to_read,self.file_mode) as file_context:
                contents=file_context.read(self.stream_size)
                while len(contents)>0:
                    yield contents
                    contents=file_context.read(self.stream_size)

        except Exception as e:

            if type(e).__name__=='IOError':
                output="You have a file input/output error  {}".format(e.args[1])
                raise Exception (output)
            else:
                output="You have a file  error  {} {} ".format(file_context.name,e.args)     
                raise Exception (output)

b=FileRead("read.txt",'r')
contents=b.file_read()

lastline = ""
for content in contents:
# print '-------'
    lastline = content
print lastline
Projesh Bhoumik
  • 1,058
  • 14
  • 17
0

I use the pandas module for its convenience (often to extract the last value).

Here is the example for the last row:

import pandas as pd

df = pd.read_csv('inputFile.csv')
last_value = df.iloc[-1]

The return is a pandas Series of the last row.

The advantage of this is that you also get the entire contents as a pandas DataFrame.

D.L
  • 4,339
  • 5
  • 22
  • 45