I have a two requirements .
First Requirement-I want to read the last line of a file and assign the last value to a variable in python.
A simple solution, which doesn't require storing the entire file in memory (e.g with file.readlines()
or an equivalent construct):
with open('filename.txt') as f:
for line in f:
pass
last_line = line
For large files it would be more efficient to seek to the end of the file, and move backwards to find a newline, e.g.:
import os
with open('filename.txt', 'rb') as f:
f.seek(-2, os.SEEK_END)
while f.read(1) != b'\n':
f.seek(-2, os.SEEK_CUR)
last_line = f.readline().decode()
Note that the file has to be opened in binary mode, otherwise, it will be impossible to seek from the end.