Move files automatically after downloading them (under Linux)

A few days ago I read an article by Joachim Schlosser on how to handle downloaded files on the Mac using Hazel.

My first idea was that this could be easily achieved with Linux, last night I found some time to work on it.

It is based on inotify, a tool to watch files and folders for changes (like e.g. adding a new file to a folder).

Googling for the right way to pass the filename of an added file to a script I came across an answer on askubuntu which I then modified to the following (I removed the ‚-r‘ parameter which checks not only the one folder but all subfolders):

inotifywait -m -q --format '%f' -e create  "/home/uwe/Downloads"  | while read FILE
do
  python inotify-handler.py $FILE
done

As I am way more familiar with Python than with BASH, I simply hand over the filename to another Python file, however the whole thing could be implemented in bash, of course.

The Python code is straightforward then as well, see the comments in the code

import sys
import os
 
folder = '/home/uwe/Downloads/'
 
# check if first parameter handed to Python is a file
if len(sys.argv) == 2:
    filename = sys.argv[1]
    if os.path.isfile(folder + filename):
        print(filename)
        # get the file extension
        file, fileext = os.path.splitext(folder + filename)
        # move only PDFs
        if fileext.lower() == '.pdf':
            # move PDFs to subfolder /home/uwe/Downloads/PDF 
            os.rename(folder + filename, folder + 'PDF/' + filename)
        else:
            print('*' + fileext.lower(), 'is not handled by this script')
    else:
        print('Not a valid filename:', folder + filename)
else:
    print('Not 2 parameters:', str(sys.argv))

This was just a basic proof of concept, one could easily extend this script to handle not just the extensions but also specific name patterns. If you use it somewhere, keep me posted!

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website