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
  python $FILE

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):
        # 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)
            print('*' + fileext.lower(), 'is not handled by this script')
        print('Not a valid filename:', folder + filename)
    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 Ziegenhagen mag LaTeX und Python, auch gern in Kombination. Hat Dir dieser Beitrag geholfen und möchtest Du Dich dafür bedanken? Dann unterstütze doch vielleicht die Dingfabrik Köln e.V. mit einem kleinen Beitrag. Details zur Bezahlung findest Du unter Spenden für die Dingfabrik.

More Posts - Website