Watching a Folder with Python: Auto-Rename, File by Month and Log Every New File

Most office computers have a few inbox folders: the PDF quotes that arrive by email, the receipts the scanner drops in automatically, the photos a colleague downloaded from WhatsApp. Once a file lands, someone still has to rename it, sort it by month and move it to the right place. A few dozen a day is not hard work, but doing it every single day wears you down.

The usual first instinct is a scheduled script that scans the folder every ten minutes. It works, but with two drawbacks: you may wait up to ten minutes, and it scans even when nothing new has arrived. A better fit is event driven: use watchdog to watch the folder and react the moment a file appears, consuming nothing in between.

Scheduled versus instant: when to use which

  • Scheduled (schedule, cron, Windows Task Scheduler): good for once-a-day work, such as producing the daily close at 11pm. It runs whether or not anything new has arrived.
  • Instant (watchdog): good for "when something arrives, act now" work such as a customer order, a scan, or a file exported by another system.

The two can coexist. watchdog renames and files each item the moment it lands; a scheduled script handles the nightly summary and backup.

Step 1: install watchdog

pip install watchdog

Pure Python, working on Windows, Mac and Linux, with no extra service to install.

Step 2: the smallest version that proves the trigger works

from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler WATCH = "D:/Inbox" class Handler(FileSystemEventHandler): def on_created(self, event): if event.is_directory: return print("new file:", event.src_path) observer = Observer() observer.schedule(Handler(), WATCH, recursive=False) observer.start() print("watching", WATCH) observer.join()

Forward slashes are fine on Windows and save you from escaping backslashes.

Run it, drop a file in, and the console should print the filename immediately. The is_directory check cannot be skipped: creating a folder fires the same event, and you will see a stream of folder names instead of files.

The third trap: the file is not finished writing

This is the problem every first attempt hits. on_created fires the instant the file appears, and at that point it may be 0 KB. Read or move it right then and you get half a file, or the source program fails because its handle has been moved away mid-write.

The fix is a wait-until-written check: read the file size every half second and treat it as complete when two consecutive reads are identical.

import os, time def wait_until_stable(path, timeout=30): last = -1 t0 = time.time() while time.time() - t0 < timeout: try: size = os.path.getsize(path) except OSError: return False if size == last and size > 0: return True last = size time.sleep(0.5) return False

Treat a timeout as failure rather than waiting forever. Some programs pause for a few seconds while writing a large file, so 30 seconds is usually enough; for video, use 120.

Step 4: rename, file and log, the full version

Assume the requirement is: a file lands in Inbox, gets renamed to date_originalname, moves into Archive by month, and leaves one log line behind.

import os, shutil, time, datetime from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler INBOX = "D:/Inbox" ARCHIVE = "D:/Archive" LOG = "D:/Inbox/_processed.log" class Handler(FileSystemEventHandler): def on_created(self, event): if event.is_directory: return src = event.src_path if not wait_until_stable(src): print("skipped (still writing):", src) return today = datetime.date.today() month_dir = os.path.join(ARCHIVE, today.strftime("%Y-%m")) os.makedirs(month_dir, exist_ok=True) name = os.path.basename(src) dst = os.path.join(month_dir, today.strftime("%Y%m%d") + "_" + name) base, ext = os.path.splitext(dst) n = 1 while os.path.exists(dst): dst = "%s_%d%s" % (base, n, ext) n += 1 shutil.move(src, dst) with open(LOG, "a", encoding="utf-8") as f: f.write("%s\t%s\n" % (datetime.datetime.now().isoformat(timespec="seconds"), dst)) print("filed:", dst) observer = Observer() observer.schedule(Handler(), INBOX, recursive=False) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join()

Three practical details. Collisions get a _1 or _2 suffix instead of being overwritten, because a customer sending two quotes with the same filename in one month is normal. The log is tab separated, so it opens cleanly in Excel and tells you which file moved where and when. recursive=False watches one level only; set it to True if Inbox has subfolders.

Step 5: notifications (optional)

For an immediate desktop popup, plyer will do it. If colleagues need it on their phones, post to a Telegram bot. The cheapest approach that survives is the log file plus a nightly scheduled summary, because frequent notifications get muted within a week.

Real numbers: an eight-person design studio

Around 40 client files arrive each day: quotes, photos, logo assets. One colleague used to process them twice a day, about 25 minutes each time, 50 minutes in total, with the occasional file missed and chased up later. With watchdog, files are renamed and filed within three seconds of landing, and the colleague only opens the log to check for anything unusual. That saves roughly 45 minutes a day, about 15 hours a month. The more valuable part is that nothing gets missed and no version gets overwritten.

When not to use it

If files arrive through a cloud sync client such as OneDrive, Dropbox or Google Drive, events fire repeatedly and the same file may be processed several times. In that case deduplicate by content hash, or switch to a scheduled scan with a processed list. Also, watchdog stops when the machine sleeps, so do not treat it as a 24-hour service. If it must run continuously, put it on a machine that stays awake, or register it at startup with Task Scheduler.

Summary

Python Tutorial: watching a folder needs no polling. watchdog is event driven, so it acts when a new file appears and consumes nothing when the folder is quiet. Three things matter: wait for the file to finish writing by checking that its size has stopped changing, handle filename collisions when renaming and moving, and write a log so failures are traceable. The whole program is under forty lines, yet it replaces tens of minutes of repetitive work every day, and it is steadier than doing it by hand.