pythonfile-handlingfile-read

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.


Solution

  • 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:

    enter image description here

    enter image description here

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

    enter image description here

    enter image description here