使用customtkinter和shutil实现跨设备文件上传:相对路径失效求助
解决相对路径上传文件不生效的问题
核心原因
你遇到的问题是因为Python的相对路径基于当前工作目录(即启动程序的目录),而非脚本文件所在的目录。如果从其他目录启动程序,"Uploads"会被创建在启动目录下,导致你误以为文件没上传成功。
解决方案:用脚本绝对路径拼接目标文件夹
使用os模块获取脚本所在的绝对路径,再拼接Uploads文件夹,这样无论在哪台设备运行,路径都是准确的。同时要确保目标文件夹存在,避免复制失败。
修改后的代码示例
import os import customtkinter from tkinter import filedialog import shutil status=customtkinter.CTkLabel(master=Add_student,width=200,height=250,text="",image=uploadpending,font=("Poppins Regular", 24)) # 获取脚本文件的绝对路径,拼接Uploads文件夹 script_dir = os.path.dirname(os.path.abspath(__file__)) uplpath = os.path.join(script_dir, "Uploads") # 确保Uploads文件夹存在,不存在则自动创建 os.makedirs(uplpath, exist_ok=True) def upload_file(): file_path = filedialog.askopenfilename() if file_path: try: shutil.copy2(file_path, uplpath) status.configure(image=Assetsuccess) except Exception as e: status.configure(text="Error uploading file: " + str(e),image=uploadfailed)
关键说明
os.path.abspath(__file__):获取当前脚本文件的绝对路径os.path.dirname():提取路径中的目录部分(去掉文件名)os.path.join():跨系统拼接路径(自动处理Windows的\和Linux/macOS的/)os.makedirs(uplpath, exist_ok=True):确保目标文件夹存在,exist_ok=True避免文件夹已存在时报错
这样修改后,无论在哪台设备运行程序,文件都会被复制到脚本所在目录下的Uploads文件夹中,完全不需要硬编码绝对路径。
内容的提问来源于stack exchange,提问作者Shubhwins
相关产品推荐
相关产品推荐

