read the last line of a file in python

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

    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.

提交回复
热议问题