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

8 Answers 8

20

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]
Sign up to request clarification or add additional context in comments.

1 Comment

This should not be used for large files since it reads them in completely, and only throws away all but the last line afterwards.
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

2 Comments

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.
the smartest solution, you are going to loop in the file in any case.
8

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())

2 Comments

what is the time gain of method 3 file.seek(-2, os.SEEK_END) over methods 1 and 2 which use in this answer ?
In your second example, why is it possible to print(line)? It would seem to me that the variable line only exists within the for loop.
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

1 Comment

Your assignment lastline = line is not really necessary and therefore inefficient. You should replace it with a simple pass statement.
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

Comments

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

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.