How To Detect File Changes Using Python
Last Updated :
27 Mar, 2024
In the digital age, monitoring file changes is essential for various applications, ranging from data synchronization to security. Python offers robust libraries and methods to detect file modifications efficiently. In this article, we will see some generally used method which is used to detect changes in file.
How To Detect File Changes Using Python?
Below, are the methods of detecting file changes in Python.
- Polling Method
- Using OS File System Events:
- Hash Comparison Method:
Detect File Changes Using Polling Method
In this example, This Python code uses the Python OS Module and time modules to monitor changes in a specified file at regular intervals. It compares the last modified timestamp of the file with its current modified timestamp, printing a message if they differ. The detect_file_changes function continuously checks for modifications until interrupted.
Python
import os
import time
def detect_file_changes(file_path, interval=1):
last_modified = os.path.getmtime(file_path)
while True:
current_modified = os.path.getmtime(file_path)
if current_modified != last_modified:
print("File has changed!")
last_modified = current_modified
time.sleep(interval)
# Usage
detect_file_changes("file.txt")
Output:

Detect File Changes Using OS File System Events
In this example, below This Python code uses the watchdog library to monitor file modifications within a specified directory. It defines a custom event handler MyHandlerwhich prints a message when a .txt file is modified. The observer is set up to watch the specified directory recursively, and upon interruption, the code gracefully stops the observer.
Python
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class MyHandler(FileSystemEventHandler):
def on_modified(self, event):
if not event.is_directory and event.src_path.endswith(".txt"):
print(f"File {event.src_path} has been modified!")
# Create observer and event handler
observer = Observer()
event_handler = MyHandler()
# Set up observer to watch a specific directory
directory_to_watch = "."
observer.schedule(event_handler, directory_to_watch, recursive=True)
# Start the observer
observer.start()
# Keep the script running
try:
while True:
pass
except KeyboardInterrupt:
observer.stop()
observer.join()
Output

Detect File Changes Using Hash Comparison Method
In this example, below Python code uses the hashlib library to calculate the SHA-256 hash of a specified file and continuously monitors changes in its hash value. If the hash value changes, indicating a modification in the file's content, the script prints a message indicating the change. The detect_file_changes function provides a simple yet effective method for real-time detection of file alterations.
Python
import hashlib
import time
def calculate_file_hash(file_path):
with open(file_path, "rb") as f:
file_hash = hashlib.sha256(f.read()).hexdigest()
return file_hash
def detect_file_changes(file_path):
last_hash = calculate_file_hash(file_path)
while True:
current_hash = calculate_file_hash(file_path)
if current_hash != last_hash:
print("File has changed!")
last_hash = current_hash
time.sleep(1)
# Usage
detect_file_changes("example.txt")
Output
methods
Similar Reads
Create a watchdog in Python to look for filesystem changes 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 mod
4 min read
How to implement File Caching in Python One of the most important ways to improve application performance in the dynamic world of Python programming is to optimize file access. The use of file caching is one effective method for accomplishing this. Developers can greatly reduce the requirement to read or create the same information by usi
6 min read
Check end of file in Python In Python, checking the end of a file is easy and can be done using different methods. One of the simplest ways to check the end of a file is by reading the file's content in chunks. When read() method reaches the end, it returns an empty string.Pythonf = open("file.txt", "r") # Read the entire cont
2 min read
Python Loop through Folders and Files in Directory File iteration is a crucial process of working with files in Python. The process of accessing and processing each item in any collection is called File iteration in Python, which involves looping through a folder and perform operation on each file. In this article, we will see how we can iterate ove
4 min read
Create a Log File in Python Logging is an essential aspect of software development, allowing developers to track and analyze the behavior of their programs. In Python, creating log files is a common practice to capture valuable information during runtime. Log files provide a detailed record of events, errors, and other relevan
3 min read
Compare Two Xml Files in Python We are given two XML files and our task is to compare these two XML files and find out if both files are some or not by using different approaches in Python. In this article, we will see how we can compare two XML files in Python. Compare Two XML Files in PythonBelow are the possible approaches to c
3 min read