Check if a file is modified in Python

Question:

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?

Asked By: Speedy Boosting

||

Answers:

def read_file():
    with open("most_recent_follower.txt", "r") as f:
        SMRF1 = f.readlines()
    return SMRF1

initial = read_file()
while True:
    current = read_file()
    if initial != current:
        for line in current:
            if line not in initial:
                print(line)
        initial = current

Read the file in once, to get it’s initial state. Then continuously repeat reading of the file. When it changes, print out its contents.

I don’t know what bot you are referring to, but this code, and yours, will continuously read the file. It never seems to exit.

Answered By: jgritty

I might suggest copying the file to a safe duplicate location, and possibly using a diff program to determine if the current file is different from the original copy, and print the added lines. If you just want lines appended you might try to utilize a utility like tail

You can also use a library like pyinotify to only trigger when the filesystem detects the file has been modified

Answered By: ThorSummoner

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
Answered By: settwi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.