python 监听文件夹工具
公司项目最近写了个监听文件夹工具,本身不是写python的,想到用while 1写循环写,跑着跑着卡,后台又用定时任务跑,效果不太理想 最后发现watchdog 包 主要可以监听 文件内的创建 更改 删除等,随时监听。网上watchdog demo ,配合根据这个修改pip install watchdogfrom watchdog.observers import Observerfrom wa
·
公司项目最近写了个监听文件夹工具,本身不是写python的,想到用while 1写循环写,跑着跑着卡,后台又用定时任务跑,效果不太理想 最后发现 watchdog 包 主要可以监听 文件内的创建 更改 删除等,随时监听。
网上watchdog demo ,配合根据这个修改
pip install watchdog
from watchdog.observers import Observer
from watchdog.events import *
import time
class FileEventHandler(FileSystemEventHandler):
def __init__(self):
FileSystemEventHandler.__init__(self)
def on_moved(self, event):
if event.is_directory:
print("directory moved from {0} to {1}".format(event.src_path, event.dest_path))
else:
print("file moved from {0} to {1}".format(event.src_path, event.dest_path))
def on_created(self, event):
if event.is_directory:
print("directory created:{0}".format(event.src_path))
else:
print("file created:{0}".format(event.src_path))
def on_deleted(self, event):
if event.is_directory:
print("directory deleted:{0}".format(event.src_path))
else:
print("file deleted:{0}".format(event.src_path))
def on_modified(self, event):
if event.is_directory:
print("directory modified:{0}".format(event.src_path))
else:
print("file modified:{0}".format(event.src_path))
if __name__ == "__main__":
observer = Observer()
event_handler = FileEventHandler()
observer.schedule(event_handler, r"C:\Users\wyq\Desktop\1", True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
更多推荐
已为社区贡献1条内容
所有评论(0)