简体   繁体   中英

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

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]

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

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

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

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

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM