你好,我想用python制作一个程序实现用webdav连接到cloudreve,但是程序一直报错找不到父目录。
恳请帮我查看一下问题,我已经改了很多次代码了,依然是这样的问题。我连接的就是 域名/dav
下载文件正常,但是上传一直无法找到目录欸
以下为代码,请帮我看看哪里的路径有错误呢
import os
import tkinter as tk
import time
import threading
from tkinter import filedialog
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from webdav3.client import Client
WebDAV 服务器配置
url = 'http://p.xwh.at/dav'
username = 'admin@xn--ubt767m.cc'
password = 'QssDenw6B4k6J6i4247xphXF7wBKtqKJ'
创建窗口
root = tk.Tk()
root.withdraw()
弹出选择文件夹对话框
if os.path.isfile("bf.txt"):
with open("bf.txt", "r") as f:
folder_path = f.read().strip()
else:
folder_path = filedialog.askdirectory(initialdir='C:/Users/')
with open("bf.txt", "w") as f:
f.write(folder_path)
if not os.path.exists(folder_path):
raise ValueError(f'Folder {folder_path} does not exist.')
将所选文件夹路径存储在foldertopath变量中
folder_to_watch = folder_path
创建 WebDAV 客户端
options = {
'webdav_hostname': url,
'webdav_login': username,
'webdav_password': password
}
client = Client(options)
class Watcher:
def init(self, folder):
self.observer = Observer()
self.folder = folder
self.remote_folder = '/dav/'
def run(self):
event_handler = Handler(self.folder, self.remote_folder)
self.observer.schedule(event_handler, self.folder, recursive=True)
self.observer.start()
try:
while True:
time.sleep(5)
except Exception as e:
self.observer.stop()
print(f"Error: {e}")
self.observer.join()
class Handler(FileSystemEventHandler):
def init(self, folder, remote_folder):
self.folder = folder
self.remote_folder = remote_folder
def on_any_event(self, event):
if event.is_directory:
return None
if event.event_type == 'created' or event.event_type == 'modified':
file_path = event.src_path
file_path = file_path.replace('\\', '/') # 将本地路径中的反斜杠替换为斜杠
file_name = os.path.basename(file_path)
print(f'Uploading file {file_name}...')
remote_path = os.path.join(self.remote_folder, file_name).replace('\\', '/')
# 检查远程目录是否存在,不存在则创建
remote_dir = os.path.dirname(remote_path)
try:
client.check(remote_dir)
except RemoteParentNotFound:
client.mkdirs(remote_dir)
# 上传文件
client.upload_file(local_path=file_path, remote_path=remote_path)
print(f'File {file_name} uploaded.')
if name == 'main':
w = Watcher(folder_to_watch.replace('/', '\'))
w.run()
with open("bf.txt", "w") as f:
f.write(folder_to_watch.replace('/', '\\'))