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.
On systems that have a tail
command, you could use tail
, which for large files would relieve you of the necessity of reading the entire file.
from subprocess import Popen, PIPE
f = 'yourfilename.txt'
# Get the last line from the file
p = Popen(['tail','-1',f],shell=False, stderr=PIPE, stdout=PIPE)
res,err = p.communicate()
if err:
print (err.decode())
else:
# Use split to get the part of the line that you require
res = res.decode().split('location="')[1].strip().split('"')[0]
print (res)
Note: the decode()
command is only required for python3
res = res.split('location="')[1].strip().split('"')[0]
would work for python2.x