- 1 year ago
Run python script when a file has been added to a folder?
To run a Python script when a file has been added to a folder, you can use a combination of a file system monitoring library and your Python script. Here's an example using the watchdog
library:
Install
watchdog
library: Open a command prompt and run the following command to install thewatchdog
library:pip install watchdog
Create the Python script: Create a Python script that will be executed when a new file is added to the folder. Here's a basic example:
pythonimport time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class MyEventHandler(FileSystemEventHandler):
def on_created(self, event):
if not event.is_directory:
print("New file created:", event.src_path)
# Add your desired actions here
# Specify the folder to monitor
folder_path = "C:/path/to/folder"
event_handler = MyEventHandler()
observer = Observer()
observer.schedule(event_handler, folder_path, recursive=False)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
Customize the script: Inside the
on_created
method of theMyEventHandler
class, you can add your desired actions that should be performed when a new file is added to the folder. For example, you could process the file, trigger another script, or perform any other required actions.Run the script: Save the Python script with a meaningful name, such as
file_monitor.py
. Open a command prompt or terminal, navigate to the directory where the script is located, and run the script using thepython
command:python file_monitor.py
The script will start monitoring the specified folder for new file creations. When a new file is added, the on_created
method will be called, and you can perform the desired actions within that method.
You can customize the script further by adding error handling, logging, or additional event handlers based on your specific requirements.
Note: Keep the script running in the background to continuously monitor the folder. If you want the script to run automatically on system startup, you can set it up as a service or schedule it using the operating system's task scheduler.