DEV Community

loading...

Python Generator Example : File Watcher

an33shk4tl4 profile image Aneesh Katla ・2 min read

Python - Generators ==> Demo using file watcher

import os
from datetime import datetime as dt
import time

def checkfile(filename):
    try:
        st = os.stat(filename)
        fmtime = st.st_mtime
    except Exception as e:
        print e.message
        return
    print "*********init modification timestamp" , dt.fromtimestamp(fmtime).ctime()
    while True:
        print 'entered while loop'
        st = os.stat(filename)
        print 'collected file stats'
        yield dt.fromtimestamp(fmtime).ctime()
        print 'yield executed'
        if dt.fromtimestamp(st.st_mtime).ctime() <> dt.fromtimestamp(fmtime).ctime():
            print "File modification changed - new file modification timestamp", dt.fromtimestamp(fmtime).ctime()
            fmtime = st.st_mtime
            print 'set new mod time inside if condition'
        else:
            print 'Mod timestamps equal'
        time.sleep(2)

chk = checkfile(r'C:\filetowatch.txt')

for i in chk:
    print chk.next()
    print '---for loop next iteration after gen call'
Enter fullscreen mode Exit fullscreen mode

Python has an interesting feature called generators which allow you to consume the benefits of a an iterator but without memory overhead.Generally, an iterator is an object in memory with a list of objects. I've written a simple code above which demonstrates how a generator works. You'll need to create another script to delete and re-create a file in order to see this working.

What's that code?

The code simply watches for file modified time and identifies if there is any change in the file. A simple file watcher program. I've used python base libraries and hence no external dependencies.

Learning

File created time won't work (atleast in windows) for the same filename because Windows does not change the create time.Check out this article for more info on "name" tunneling

Feel free to leave your feedback...

Discussion (1)

pic
Editor guide
Collapse
an33shk4tl4 profile image
Aneesh Katla Author

Adding code to delete-->re-create file in windows -
save this as a .cmd or a .bat file

del c:\filetowatch.txt
REM timeout /T 3
echo "Hello" > c:\filetowatch.txt