Print Last Line of File Read In with Python

2020-06-20 07:52发布

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

标签: python
6条回答
三岁会撩人
2楼-- · 2020-06-20 08:32

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
查看更多
叼着烟拽天下
3楼-- · 2020-06-20 08:33

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
查看更多
狗以群分
4楼-- · 2020-06-20 08:48

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
查看更多
一纸荒年 Trace。
5楼-- · 2020-06-20 08:50

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
查看更多
够拽才男人
6楼-- · 2020-06-20 08:51

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
查看更多
Rolldiameter
7楼-- · 2020-06-20 08:55

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]
查看更多
登录 后发表回答