Collecting new document files for easy attachment in email

I find that I frequently (many times daily) have to send files as email attachments. Depending on the task, the files can be located in a half-dozen or so places on the Windows file system. I found myself browsing (from Outlook's "Attach File" function) to my Documents, Downloads, Desktop, or one of several network drives for the file I just saved there a few seconds ago.

I had the idea that those folders could all be monitored, with copies of the most recent files from each kept in a single place. That way, I can just always go to that one place and have access to the file I want to attach.

Requirements:

  • Automatically make a copy of the most recent files saved in any of a collection of folders of my choosing
  • Automatically purge those copies after a (short) time, because if I didn't need them for email attachment right away, I don't need them at all.

I decided to piece together a Python script to help with this job. I never worked with the watchdog library before, but found it well-suited for this. The basic layout/template for a script using watchdog to monitor a folder for new or modified files was found in this blog post by Bruno Rocha.

I got additional help with setting up the observer to watch multiple folders from Generating multiple observers with Python watchdog.

For ease, I separated the settings for the script out to a settings.ini file (attached). Just place both files in the same folder, customize the settings.ini file to fit your needs, and run the python script.

Some lessons learned and additional thoughts:

  • When the script first started taking shape, it kept running into a FileNotFoundError. I added in a short (1 second) delay between the detection of the change and the start of the copying process. This still looks 'instant' from the user perspective, but apparently gives the Operating System time to finish writing the file. Maybe...Python/watchdog was too fast!?
  • Initially, I was monitoring the created and modified events, but found that modified always occurs anyway, so ultimately just went with that.
  • I considered handling times when a file is renamed/moved within a monitored folder, but those situations don't happen a lot with files that are about to be sent as email attachments.
  • The script was trying to grab everything, including things like temp files (.tmp) and Outloook (.pst) files. So that led to locating the ignore_patterns attribute of watchdog.events.PatternMatchingEventHandler. It might have been just as easy to use patterns attribute to include only the file extensions I care about.
  • I added in a little bit of exception handling so the script won't be as likely to crash when it has a problem copying a file.

Attachment: 

Tags: 

2017-07-16, 02:07 pm