简体   繁体   中英

Can I read the last line from txt file when the file's size change? (in python)

I used this:

while (True):
    with open('filename.txt') as f:
        for line in f:
            pass
        last_line_char = line[0]

But I want to read when the file's last line or size is change. Not always.

I think the following should help. It checks the size of the text file, if any change in the text, it will inform you with the last line.

    len_data = [1,1]
    
    #print(len(data))
def my_func():
    while (True):
        with open("text_text.txt") as g:
            data2 = g.read()
        len_data.append(len(data2))
        len_each_time = len(len_data)
        if len_data[len_each_time-2] != len_data[len_each_time-1]:
            with open("text_text.txt") as f:
                data = f.readlines()
            print(data[-1])

my_func()

The output when there is no change:

在此处输入图像描述

在此处输入图像描述

I have edited the files several times, and see the output.

在此处输入图像描述

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM