3

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?

1
  • By "modified" you meant added new line? Commented Jan 21, 2015 at 0:01

3 Answers 3

5

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
Sign up to request clarification or add additional context in comments.

Comments

2
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.

5 Comments

OP wants only the new next entered if the file is modified, not the whole file contents.
I have just tried your code, the problem is that it keeps printint "current" for ever, how can I fix this?
It shouldn't ever print "current", but I updated it to only print new lines added to the file.
Tried it again, it still loops printing the new value inside the text file :S
That last line should fix it.
0

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

1 Comment

Thanks for the reply, but I tried jgritty code and it works as I desired! Thanks anyway :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.