read the last line of a file in python

后端 未结 6 1890
[愿得一人]
[愿得一人] 2021-02-01 09:25

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.

6条回答
  •  耶瑟儿~
    2021-02-01 09:54

    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
    

    Topics covered here:

    • Reading text files
    • Making a Python List of lines from the content, to make it easy to get the last line using the zero-based index len(List) -1.
    • Using find to get index locations of a string within a string
    • Using slice to obtain substrings

    All 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

提交回复
热议问题