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
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.
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.
The new line character in Python is \n . It is used to indicate the end of a line of text.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With