Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a file is modified in Python

Tags:

python

file

I am trying to create a box that tells me if a file text is modified or not, if it is modified it prints out the new text inside of it. This should be in an infinite loop (the bot sleeps until the text file is modified).

I have tried this code but it doesn't work.

while True:
    tfile1 = open("most_recent_follower.txt", "r")
    SMRF1 = tfile1.readline()
    if tfile1.readline() == SMRF1:
        print(tfile1.readline())

But this is totally not working... I am new to Python, can anyone help me?

like image 650
Speedy Boosting Avatar asked May 26 '26 08:05

Speedy Boosting


1 Answers

This is the first result on Google for "check if a file is modified in python" so I'm gonna add an extra solution here.

If you're curious if a file is modified in the sense that its contents have changed, OR it was touched, then you can use os.stat:

import os
get_time = lambda f: os.stat(f).st_ctime

fn = 'file.name'
prev_time = get_time(fn)

while True:
    t = get_time(fn)
    if t != prev_time:
        do_stuff()
        prev_time = t
like image 67
settwi Avatar answered Jun 04 '26 23:06

settwi