How it works
The script uses the watchdog library to watch a
folder in the background and react whenever a new file shows
up.
event_handler = Handler()
observer = watchdog.observers.Observer()
observer.schedule(event_handler, watchpath, recursive=False)
observer.start()
observer.join()
observer.schedule tells watchdog which folder to
watch, recursive=False means it only watches
that top-level folder, not subfolders inside it.
observer.join() keeps the script alive and
listening indefinitely.
Handling a new file
Every time a new file appears in the watched folder,
on_created fires.
def on_created(self,event):
if not event.is_directory:
time.sleep(10)
try:
endpoint = event.src_path.rindex('.')
end = event.src_path[endpoint+1:]
namepoint = event.src_path.rindex('\\')
name = event.src_path[namepoint+1:]
path = watchpath + '\\folders\\' + end + ' files\\'
if not os.path.exists(path):
os.makedirs(path)
shutil.move(event.src_path,path + name)
except:
pass
The time.sleep(10) matters more than it looks.
Browsers write a file to disk while it's downloading, and a
"created" event can fire before the download is actually
finished. Waiting 10 seconds gives the download time to
complete before the script tries to move a file that's still
being written to.
From there it's string slicing: find the last .
to get the extension, find the last \ to get
the filename, then build a destination path like
Downloads\folders\pdf files\ and move the file
there, creating the folder first if it doesn't exist
yet.
Running in the background
The file extension is .pyw instead of
.py, that runs the script without opening a
console window. Combined with adding it to Windows startup,
it just runs quietly in the background from boot, sorting
downloads as they come in without needing to be manually
started.