|
| 1 | +import os |
| 2 | +from watchdog.observers import Observer |
| 3 | +from watchdog.events import FileSystemEventHandler |
| 4 | +import shutil |
| 5 | +class MyHandler(FileSystemEventHandler): |
| 6 | + def on_created(self, event): |
| 7 | + if not event.is_directory: |
| 8 | + file_path = event.src_path |
| 9 | + file_name = os.path.basename(file_path) |
| 10 | + file_extension = os.path.splitext(file_name)[1].lower() |
| 11 | + # A dictionary takes file extensions & folder to move each formats to. |
| 12 | + destination_mapping = { |
| 13 | + # Key = Format/extension to handle : Value = Folder to move file format. |
| 14 | + ".zip": r"C:\Users\Precious pc\Documents\Zip files", |
| 15 | + ".png": r"C:\Users\Precious pc\Documents\png_files", |
| 16 | + ".psd": r"C:\Users\Precious pc\Documents\psd_destination", |
| 17 | + ".pdf": r"C:\Users\Precious pc\Documents\pdf_files", |
| 18 | + } |
| 19 | + # Default destination for unknown extensions |
| 20 | + other_files = r"C:\Users\Precious pc\Documents\other_files" |
| 21 | + # Get the destination directory for the file extension or use the default |
| 22 | + destination = destination_mapping.get(file_extension, other_files) |
| 23 | + # Move the file to the determined destination |
| 24 | + # Check if file already exists in destination & delete it. |
| 25 | + if os.path.exists(os.path.join(destination, file_name)): |
| 26 | + print(f"File {file_name} already exists in the destination. Deleting it.") |
| 27 | + os.remove(os.path.join(destination, file_name)) |
| 28 | + # Move the file to the determined destination |
| 29 | + shutil.move(file_path, destination) |
| 30 | +if __name__ == "__main__": |
| 31 | + folder_to_watch = r"C:\Users\Precious pc\Documents\monitor" # Replace with the directory you want to monitor |
| 32 | + event_handler = MyHandler() |
| 33 | + observer = Observer() |
| 34 | + observer.schedule(event_handler, path=folder_to_watch, recursive=False) # Set recursive to True if you want to monitor subdirectories |
| 35 | + observer.start() |
| 36 | + try: |
| 37 | + while True: |
| 38 | + pass |
| 39 | + except KeyboardInterrupt: |
| 40 | + observer.stop() |
| 41 | + observer.join() |
0 commit comments