问题描述
我正在使用wathdog检测新文件,在windows操作系统中使用watchdog python模块修改文件。
但是无法检测文件路径
我的代码位于类似 L:\my_code\watch.py(在 L 驱动器中)的位置
import time
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
def on_created(event):
print(f"hey,{event.src_path} has been created!")
def on_deleted(event):
print(f"Someone deleted {event.src_path}!")
def on_modified(event):
print(f"hey,{event.src_path} has been modified")
def on_moved(event):
print(f"hey,someone moved {event.src_path} to {event.dest_path}")
if __name__ == "__main__":
patterns = ["*"]
ignore_patterns = None
ignore_directories = False
case_sensitive = True
my_event_handler = PatternMatchingEventHandler(patterns,ignore_patterns,ignore_directories,case_sensitive)
my_event_handler.on_created = on_created
my_event_handler.on_deleted = on_deleted
my_event_handler.on_modified = on_modified
my_event_handler.on_moved = on_moved
from pathlib import Path
str_path = "\L\_REC"
path = r"L:\_REC"
#path = 'L:\\_REC'
go_recursively = True
my_observer = Observer()
my_observer.schedule(my_event_handler,path,recursive=go_recursively)
my_observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
my_observer.stop()
my_observer.join()
我需要检测 L:\_REC 目录下的文件更改,但出现以下错误
& 'C:\Users\vcimalap\AppData\Local\Programs\Python\python39\python.exe' 'c:\Users\vcimalap\.vscode\extensions\ms-python.python-2021.5.829140558\pythonFiles\lib\python\debugpy\launcher' '57901' '--' 'l:\External\watch_service.py'
Traceback (most recent call last):
File "l:\External\watch_service.py",line 71,in <module>
my_observer.start()
File "C:\Users\vcimalap\AppData\Local\Programs\Python\python39\lib\site-packages\watchdog\observers\api.py",line 256,in start
emitter.start()
File "C:\Users\vcimalap\AppData\Local\Programs\Python\python39\lib\site-packages\watchdog\utils\__init__.py",line 93,in start
self.on_thread_start()
File "C:\Users\vcimalap\AppData\Local\Programs\Python\python39\lib\site-packages\watchdog\observers\read_directory_changes.py",line 66,in on_thread_start
self._handle = get_directory_handle(self.watch.path)
File "C:\Users\vcimalap\AppData\Local\Programs\Python\python39\lib\site-packages\watchdog\observers\winapi.py",line 316,in get_directory_handle
return CreateFileW(path,FILE_LIST_DIRECTORY,WATCHDOG_FILE_SHARE_FLAGS,File "C:\Users\vcimalap\AppData\Local\Programs\Python\python39\lib\site-packages\watchdog\observers\winapi.py",line 112,in _errcheck_handle
raise ctypes.WinError()
FileNotFoundError: [WinError 3] The system cannot find the path specified.
PS L:\External>
解决方法
正确检查错误。它说文件:“l:\External\watch_service.py” 请将 L: 更新为 l: