Run python script when a file has been added to a folder?

Is it possible to run a Python script when a file has been added to a folder?

In my scenario I have a folder that contains movies and the Python script gets the details (name, year, plot, rating, etc) from OMDb and puts them into a file, which MySQL uses.

Every time I add a movie I have to run the Python script.

I want to know if it is possible to automatically run the Python script when a file has been added to the folder?

Thanks in advance.

2

3 Answers

Considering a unique folder where you add files often.

  • Build a script (Python and Bash are good options) that loops for folder size every 'n' seconds (or minutes, how often do you add files?).

  • Whenever a new file is created, the size will change and the script should trigger a function that search the last file added and get necessary file info and launches your Python script.

You could easily integrate the above descriptions to your existing Python script.

If you have several folders, you could make it recursive.

Let me know if you can't realize how to do it and I will help you.

Good luck!

Create a wrapper script watch_folder:

#!/bin/bash
FILE="$1"
if [ "${FILE##*.}" = "mov" ]
then your_python_script "$2/$1"
fi
exit 0

Make it executable:

chmod +x watch_folder

Watch your folder:

inoticoming your_movie_folder path_of_watch_folder_script {} your_movie_folder \;

Your Python script is started on every new file in the folder with the full path of the file name.

1

Based on lenord's solution, here is the python script.

import os
import time
# define path for file
source = "path_to_folder"
while True: if [f for f in os.listdir(source) if not f.startswith('.')] != []: # Some Work time.sleep(5) # Its just to wait if 'Some Work' is very small else: print('Empty') time.sleep(5)

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like