Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python:Detect if the current line in file read is the last one

Tags:

python

I am reading a file in Python line by line and I need to know which line is the last one while reading,something like this:

 f = open("myfile.txt")
 for line in f:
    if line is lastline:
       #do smth

From the examples I found it involves seeks and complete file readouts to count lines,etc.Can I just detect that the current line is the last one? I tried to go and check for "\n" existence ,but in many cases the last lines is not followed by backslash N.

Sorry if my question is redundant as I didn't find the answer on SO

like image 549
Michael IV Avatar asked Jul 27 '14 16:07

Michael IV


People also ask

How do you find the last line of a file in Python?

To find the last line of a large file in Python by seeking: Open the file in binary mode. Seek to the end of the file. Jump back the characters to find the beginning of the last line.

How do you check if a line is present in a file in Python?

Method 1: Finding the index of the string in the text file using readline() In this method, we are using the readline() function, and checking with the find() function, this method returns -1 if the value is not found and if found it returns 0.

How do I find the last line of a string in Python?

The new line character in Python is \n . It is used to indicate the end of a line of text.

How does readline () know where each line is?

readline reads each line in order. It starts by reading chunks of the file from the beginning. When it encounters a line break, it returns that line. Each successive invocation of readline returns the next line until the last line has been read.


1 Answers

import os
path = 'myfile.txt'
size = os.path.getsize(path)
with open(path) as f:
    for line in f:
        size -= len(line)
        if not size:
            print('this is the last line')
            print(line)

Here is an alternative solution, in case it's a really large file, that takes a long time to traverse. The file is read in reverse from end to beginning using seek. It assumes the file is not binary and not compressed and has at least one line break and the very last character is a line break.

import os
path = 'myfile.txt'
size = os.path.getsize(path)
with open(path) as f:
    for i in range(1, size):
        f.seek(size - 1 - i)
        if f.read(1) == '\n':
            print('This is the last line.:')
            last_line = f.read()
            print(last_line)
            break
like image 198
tommy.carstensen Avatar answered Sep 22 '22 12:09

tommy.carstensen