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.
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