
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How to monitor Python files for changes?
Monitoring files for changes in any language is hard because of cross platform issues. On python, there is a widely used cross platform library called watchdog that allows watching for changes. You can install it using:
$ pip install watchdog
Example
To watch a file called 'my_file.txt' using watchdog, you can use the simple program:
import time from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler class MyHandler(FileSystemEventHandler): def on_modified(self, event): print("Got it!") event_handler = MyHandler() observer = Observer() observer.schedule(event_handler, path='.', recursive=False) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join()
When you run this program and make any changes to any file in current directory, the on_modified function from MyHandler class gets called with the event. In the MyHandler class you can define your own functions to handle the events. In the path, you can specify the files/directories you want to monitor. To stop this program, use Ctrl + C
- Related Articles
- 4 Ways to Watch or Monitor Log Files in Real Time
- How to setup VIM autoindentation properly for editing Python files?
- How to convert PDF files to Excel files using Python?
- How to import other Python files?
- How to compare files in Python
- Python Support for gzip files (gzip)
- How to remove swap files using Python?
- How to Crack PDF Files in Python?
- How to create powerpoint files using Python
- How to Monitor Collections in Postman?
- How to rename multiple files recursively using Python?
- How to safely open/close files in Python?
- How to scrape through Media Files in Python?
- Psensor graphical hardware temperature monitor for linux
- How to Connect a Laptop to a Monitor?

Advertisements