![]() |
VOOZH | about |
Many times a file is needed to be processed at the time of its creation or its modification. This can be done by following changes in a particular directory. There are many ways in python to follow changes made in a directory. One such way is to use the watchdog module. As the name suggests this module observes the given directory and can notify if a file is created or changed.
pip install watchdog
Now let's dive into the code that will log all the changes registered. This code will log changes registered only in the current directory.
Output: 👁 watchdog-Python
The above code will log all the changes registered in a directory. If you want to make changes at the time a file is created or modified, you can do so by using the following code.
Output: 👁 python-watchdog
The Observer is the class that watches for any file system change and then dispatches the event to the event handler. It monitors the file system and look for any changes.
The event handler is an object that will be notified when something happens to the file system. In general a script is written to watch over any type of new files created or modified like jpg, xml etc. For example, in the code below the PatternMatchingEventHandler inherits from the FileSystemEventHandler class and is used to do just that. Some useful methods of this class are:
Each one of those methods receives the event object as first parameter, and the event object has 3 attributes:
The below script is used to observe only .csv files using the PatternMAtchingEventHandler. You can further extend the patterns list if you want to observe more than one type of file.
Output: 👁 watchdog-python
Here with help of PatternMAtchingEventHandler we can take advantage of processing just events related with files with the .csv extension. By extending an event handler class provided by Watchdog we gain the ability to handle modified, created, deleted and moved events by implementing the class methods described above.