Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python library to detect if a file has changed between different runs?

Tags:

python

file

Suppose I have a program A. I run it, and performs some operation starting from a file foo.txt. Now A terminates.

New run of A. It checks if the file foo.txt has changed. If the file has changed, A runs its operation again, otherwise, it quits.

Does a library function/external library for this exists ?

Of course it can be implemented with an md5 + a file/db containing the md5. I want to prevent reinventing the wheel.

like image 356
Stefano Borini Avatar asked Dec 16 '09 05:12

Stefano Borini


People also ask

How do I see directory changes in Python?

Autoreload is a simple python script to watch a directory for changed files and restarts a process when the change is detected. For instance, I run ./autoreload python main.py. This first runs python main.py, then watches the current working directory and all subdirectories for changes.

How do I check if a file exists in Python?

In Python, you can check whether certain files or directories exist using the isfile() and isdir() methods, respectively. However, if you use isfile() to check if a certain directory exists, the method will return False . Likewise, if you use if isdir() to check whether a certain file exists, the method returns False .


1 Answers

FYI - for those using this example who got this error: "TypeError: can't pickle HASH objects" Simply modify the following (optionally update md5 to hashlib, md5 is deprecated):

    import pickle
    import hashlib #instead of md5
    try:
        l = pickle.load(open("db"))
    except IOError:
        l = []
    db = dict(l)
    path = "/etc/hosts"
    #this converts the hash to text
    checksum = hashlib.md5(open(path).read()).hexdigest() 
    if db.get(path, None) != checksum:
        print "file changed"
        db[path] = checksum
    pickle.dump(db.items(), open("db", "w"))

so just change:

    checksum = hashlib.md5(open(path).read())

to

    checksum = hashlib.md5(open(path).read()).hexdigest()
like image 170
James Nelson Avatar answered Sep 28 '22 05:09

James Nelson