read the last line of a file in python

后端 未结 6 1715
[愿得一人]
[愿得一人] 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 10:15

    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

提交回复
热议问题