watchdog python實例化一個監控多個文件夾内新增文件的脚本,請給出三個不同的脚本並自行測試
时间: 2024-09-16 12:04:35 浏览: 61
在Python中,可以使用`watchdog`库来创建一个监控多个文件夹并检测新添加文件的简单脚本。首先,你需要安装`watchdog`库,可以使用pip安装:
```bash
pip install watchdog
```
以下是三个不同的脚本示例,每个脚本分别使用了`Observer`来监听指定目录的变化,并触发回调函数当有新的文件添加:
### 示例一 - 监听单个文件夹
```python
import os
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class NewFileHandler(FileSystemEventHandler):
def on_modified(self, event):
if event.is_directory:
return
print(f"New file detected: {event.src_path}")
def monitor_folder(path):
event_handler = NewFileHandler()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
# 替换为你要监控的文件夹路径
monitor_folder("/path/to/your/folder")
```
### 示例二 - 监听多个文件夹 (使用列表)
```python
import os
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
folders_to_watch = ["/path/to/folder1", "/path/to/folder2"]
class MultiFolderHandler(FileSystemEventHandler):
def __init__(self):
self.folders = folders_to_watch
def on_modified(self, event):
# ... (处理逻辑同上)
def start_monitors():
event_handler = MultiFolderHandler()
observers = {}
for folder in event_handler.folders:
observer = Observer()
observer.schedule(event_handler, folder, recursive=True)
observers[folder] = observer
for observer in observers.values():
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
for observer in observers.values():
observer.stop()
for observer in observers.values():
observer.join()
start_monitors()
```
### 示例三 - 使用装饰器自动注册监听
```python
import os
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
@observer.register
def handle_file_system_event(observer, event):
if event.is_directory:
return
print(f"New file detected: {event.src_path}")
@observer.register
def monitor_folder(path):
observer.schedule(handle_file_system_event, path, recursive=True)
if __name__ == "__main__":
observer = Observer()
observer.start()
# 替换为你要监控的文件夹路径
monitor_folder("/path/to/your/folder")
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
```
记得替换`"/path/to/your/folder"`为实际要监控的文件夹路径,然后运行脚本来测试。
阅读全文