Watchdog实现文件下载自动转移

一段时间观察某个文件夹,如果有新文件下载直接移动到新目录

# *
# *  @author Zhaoliang Ye 叶昭良(zl_ye@qny.chng.com.cn)
# *  @version V0.1
# *  @Title: autoMoveFilesByWatchdog.py
# *  @Description: 自动移动某个指定文件夹 到新的目录下, 当有新文件进入后 直接复制过去
## 需要安装watchdog
# *  @Time: 2022/2/11 22:36
# *

oldDirectory="d://test1"
newDirectory="d://test2"

from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
import os
import time
class MyHandler(FileSystemEventHandler):
    def on_modified(self,event):
        for filename in os.listdir(oldDirectory):
            src= oldDirectory+"/"+filename
            target=newDirectory+"/"+filename
            print(f'oldFilename={src}  \t newFilename={target} ')
            os.rename(src,target)
            print(f'\033[1;31m move file {filename} from {oldDirectory}  to {newDirectory}')

event_handler=MyHandler()
observer=Observer()
observer.schedule(event_handler,oldDirectory,recursive=True)
observer.start()

try:
    while True:
##间隔10s
        time.sleep(10)
except KeyboardInterrupt:
    observer.stop()
observer.join()
Related
叶昭良
叶昭良
Engineer of offshore wind turbine technique research

My research interests include distributed energy, wind turbine power generation technique , Computational fluid dynamic and programmable matter.