DEV Community

Free Python Code
Free Python Code

Posted on

Python script that triggers an alarm when a file is pasted or created in a specific directory

created by : YouCode

import time
import winsound
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

class FileChangeHandler(FileSystemEventHandler):
    def on_created(self, event):
        if not event.is_directory:
            print(f'File {event.src_path} was created')
            play_alarm_sound()

def play_alarm_sound():
    winsound.PlaySound("SystemAsterisk", winsound.SND_ALIAS)

if __name__ == "__main__":
    path = 'path_to_directory'  # replace with the directory path you want to monitor

    event_handler = FileChangeHandler()
    observer = Observer()
    observer.schedule(event_handler, path, recursive=False)
    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()

    observer.join()

Enter fullscreen mode Exit fullscreen mode

In this script, we define the FileChangeHandler class that inherits from FileSystemEventHandler and overrides the on_created method. When a file is created in the monitored directory, the on_created method is called, and it prints a message and plays the alarm sound by calling the play_alarm_sound function.

To use the script, replace 'path_to_directory' with the actual path to the directory you want to monitor for file creations. The script will continuously run and trigger the alarm whenever a new file is created in the specified directory.

Please note that this script is specifically designed for Windows systems due to the use of the winsound library for playing the alarm sound. If you are using a different operating system, you will need to modify the play_alarm_sound function to use a different method for playing sounds.

Also, make sure you have the necessary permissions to access the monitored directory and that your system has sound capabilities.

Top comments (0)