How do I watch a file for changes? How do I watch a file for changes? python python

How do I watch a file for changes?

Did you try using Watchdog?

Python API library and shell utilities to monitor file system events.

Directory monitoring made easy with

  • A cross-platform API.
  • A shell tool to run commands in response to directory changes.

Get started quickly with a simple example in Quickstart...

If polling is good enough for you, I'd just watch if the "modified time" file stat changes. To read it:


(Also note that the Windows native change event solution does not work in all circumstances, e.g. on network drives.)

import osclass Monkey(object):    def __init__(self):        self._cached_stamp = 0        self.filename = '/path/to/file'    def ook(self):        stamp = os.stat(self.filename).st_mtime        if stamp != self._cached_stamp:            self._cached_stamp = stamp            # File has changed, so do something...

Have you already looked at the documentation available on If you only need it to work under Windows the 2nd example seems to be exactly what you want (if you exchange the path of the directory with one of the files you want to watch).

Otherwise, polling will probably be the only really platform-independent option.

Note: I haven't tried any of these solutions.