Windows平台Python实现目录新增子文件夹监控及MP4路径提取求助
解决Windows下监控目录并提取新增子文件夹中MP4文件的问题
No worries, the watchdog library works perfectly on Windows for this exact scenario. Let's turn your pseudocode into a working Python script that monitors your target directory, detects new subfolders, and grabs all MP4 file paths inside them.
Step 1: Install Watchdog
First, make sure you have the library installed. Open a command prompt and run:
pip install watchdog
Step 2: Full Working Code
Here's a complete script that implements your requirement. I've added comments to explain each part:
import time import os import glob from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler class FolderMonitorHandler(FileSystemEventHandler): def __init__(self, watch_folder): self.watch_folder = watch_folder def on_created(self, event): # Only react to new folders (ignore files directly created in the watch folder) if event.is_directory: # Wait a tiny bit to ensure the folder is fully created (avoids race conditions) time.sleep(0.5) new_folder_path = event.src_path print(f"New subfolder created: {new_folder_path}") # Find all MP4 files in the new subfolder mp4_files = glob.glob(os.path.join(new_folder_path, "*.mp4")) if mp4_files: print("Found MP4 files:") for mp4_path in mp4_files: print(f"- {mp4_path}") else: print("No MP4 files found in this subfolder.") if __name__ == "__main__": # Set your target watch folder here WATCH_FOLDER = "C:/watchfolder" # Initialize the event handler and observer event_handler = FolderMonitorHandler(WATCH_FOLDER) observer = Observer() observer.schedule(event_handler, path=WATCH_FOLDER, recursive=False) # Recursive=False means only monitor top level for new folders # Start the observer print(f"Monitoring folder: {WATCH_FOLDER}") observer.start() # Keep the script running until interrupted (Ctrl+C) try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join()
Key Details to Note:
- Recursive Monitoring: The script uses
recursive=Falsebecause we only care about new folders directly created inC:/watchfolder, not nested subfolders. If you want to monitor nested folders too, change this toTrue. - Race Condition Fix: The small
time.sleep(0.5)ensures the folder is fully created before we scan it—sometimes Windows takes a split second to finalize folder creation. - MP4 Detection: We use
glob.glob()to easily find all.mp4files. This is simpler than manually walking the directory for this use case.
How to Use:
- Replace
"C:/watchfolder"with your actual target directory path. - Save the script as
folder_monitor.py. - Run it from the command prompt:
python folder_monitor.py. - Leave the script running in the background—it will automatically detect new folders and print their MP4 files as they're added.
内容的提问来源于stack exchange,提问作者Harsh Nagarkar
相关产品推荐
相关产品推荐

