我需要制作一个程序,并要求其中有上传文件的功能,我该怎么做?

问题描述 投票:0回答:1

我正在使用customtkinter和shutil,我已经完成了基本功能并且文件被上传,但仅当我使用确定路径时,当我使用相对路径时它不起作用 我希望我的程序可以在任何设备上运行,所以显然我不能使用明确的路径。有什么办法可以绕过这个吗?就像任何可以在不同计算机中为我提供明确路径的模块一样,以便我可以使用它或可以在 f 字符串中添加的凭据或另一个模块,该模块可以像 Shutil 这样的相对路径运行。

代码是这样的:

status=customtkinter.CTkLabel(master=Add_student,width=200,height=250,text="",image=uploadpending,font=("Poppins Regular", 24))
  
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)

这里如果我放-

uplpath="Uploads"

然后显示上传成功,但指定的文件夹中没有上传任何文件。

仅当我添加明确的路径(如-

)时才会上传文件

uplpath="C:\\Users\\user\\Documents\\Coding files\\project\\Admin Window\\Uploads"

python-3.x file-upload shutil customtkinter
1个回答
0
投票

如果你想获取另一个文件所在的目录 在这种情况下

os.path.dirname(file_path)

将为您提供相对于其他文件的绝对路径。

然后你可以用

uplpath

加入它

os.path.join(os.path.dirname(file_path), uplpath)

© www.soinside.com 2019 - 2024. All rights reserved.