Desktop organization with Python

Stokry - Sep 29 '20 - - Dev Community

Today I will show you how to build a simple desktop organization script using the watchdog module, which observes the Desktop for any changes.
The basic idea is when you put a file on a desktop it will automatically be deleted and moved to a given folder.

import watchdog.events
import watchdog.observers
import shutil

class Handler(watchdog.events.PatternMatchingEventHandler):
    def __init__(self):
        watchdog.events.PatternMatchingEventHandler.__init__(self, patterns=['*.txt', '*.png', '*.jpg'], ignore_patterns = None,
                                                     ignore_directories = False, case_sensitive = True)

    def on_created(self, event):
        print(f"Created at {event.src_path}")
        if event.src_path.endswith('.txt'): 
            shutil.move(event.src_path, r'C:\Users\Stokry\Desktop\Text_Documents')          
        elif event.src_path.endswith('.png') or event.src_path.endswith('.jpg'): 
            shutil.move(event.src_path, r'C:\Users\Stokry\Desktop\Image_docs')              
    def on_deleted(self, event):
        print(f"Deleted at {event.src_path}")

event_handler = Handler()
observer = watchdog.observers.Observer()
observer.schedule(event_handler, r'C:\Users\Stokry\Desktop', recursive = False)
observer.start()
observer.join()

Enter fullscreen mode Exit fullscreen mode

This is a very simple way to do it, you can build a more complex script.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .