watchfiles: A handy Python library to watch for file changes
Operating systems provide APIs that allow programs to be notified about changes in the filesystem, such as when files are created, modified, deleted, or renamed.
Programs can register interest in those events, similar to subscribing to a topic, and react when they occur, for example by running code.
In Python you can do that using the watchfiles library (which is indeed a wrapper around the Rust notify-rs crate, so it is fast!).
The basic usage is pretty straight forward – and elegant:
from watchfiles import watch
for changes in watch('./path/to/dir'):
print(changes)
# Do anything hereThat’s basically an infinite loop hooked to the notifications.
You can access the changes set of tuples that look like this:
{(<Change.added: 1>, '/path/to/the/added/file')}
{(<Change.modified: 2>, '/path/to/the/modified/file')}
{(<Change.deleted: 3>, '/path/to/the/deleted/file')}/Fin
Any bugs, questions, comments, suggestions? Ping me on twitter or drop me an e-mail (fabridamicelli at gmail).
Share this article on your favourite platform: