VOOZH about

URL: https://www.geeksforgeeks.org/python/how-to-detect-file-changes-using-python/

⇱ How To Detect File Changes Using Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How To Detect File Changes Using Python

Last Updated : 23 Jul, 2025

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.

Output:

👁 Recording-2024-02-22-101704

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.

Output

👁 ezgif-6-fd42b6c89b

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.

Comment