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.
He's not just asking how to read lines in the file, or how to read the last line into a variable. He's also asking how to parse out a substring from the last line, containing his target value.
Here is one way. Is it the shortest way? No, but if you don't know how to slice strings, you should start by learning each built-in function used here. This code will get what you want:
# Open the file
myfile = open("filename.txt", "r")
# Read all the lines into a List
lst = list(myfile.readlines())
# Close the file
myfile.close()
# Get just the last line
lastline = lst[len(lst)-1]
# Locate the start of the label you want,
# and set the start position at the end
# of the label:
intStart = lastline.find('location="') + 10
# snip off a substring from the
# target value to the end (this is called a slice):
sub = lastline[intStart:]
# Your ending marker is now the
# ending quote (") that is located
# at the end of your target value.
# Get it's index.
intEnd = sub.find('"')
# Finally, grab the value, using
# another slice operation.
finalvalue = sub[0:intEnd]
print finalvalue
The print command output should look like this:
filename.txt
len(List) -1
.find
to get index locations of a string within a stringslice
to obtain substringsAll of these topics are in the Python documentation - there is nothing extra here, and no imports are needed to use the built-in functions that were used here.
Cheers,
-=Cameron
Example from https://docs.python.org/3/library/collections.html
from collections import deque
def tail(filename, n=10):
'Return the last n lines of a file'
with open(filename) as f:
return deque(f, n)
Why you just read all the lines and store the last line to the variable?
with open('filename.txt', 'r') as f:
last_line = f_read.readlines()[-1]
You can read and edit all the line doing something like:
file = open('your_file.txt', 'r')
read_file = file.readlines()
file.close()
file1 = open('your_file.txt', 'w')
var = 'filename.txt'
for lec in range(len(read_file)):
if lec == 1:
file1.write('<context:property-placeholder location="%s"/>' % var)
else:
file1.write(read_file[lec])
file1.close()
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