【问题标题】:How could I prompt the user to provide a path to store the files?如何提示用户提供存储文件的路径?
【发布时间】:2021-12-15 10:48:27
【问题描述】:

该程序从urls.txt 文件中提供的链接下载文件,并假定python 脚本和urls.txt 位于同一文件夹中。如何更改程序以要求用户提供存储文件的路径并更新 urlretrieve 行?我怎样才能让程序打印正在下载的当前链接和正在下载的文件的名称?

import os.path
import urllib.request

links = open('urls.txt', 'r')
for link in links:

    # Get one line of text (e.g. http://server/files/grades.doc),
    # then get the filename from the end of the URL
    link = link.strip()
    filename = link.rsplit('/', 1)[-1]

    # Does this file exist in this folder? If not, download it
    if not (os.path.isfile(filename)):
        print('Downloading: ' + filename)
        try:
            urllib.request.urlretrieve(link, filename)
            print("File size was", os.path.getsize(filename))
        except Exception as inst:
            print(inst)
            print('  Encountered unknown error. Continuing.')

    # File exists; don't download
    else:
        print("This file exists already.")

# End of program
print("Finished downloading.")

要求是:

【问题讨论】:

    标签: python script


    【解决方案1】:

    提示用户的方式有很多种。一种是在开始时通过命令行询问,然后将字符串输入转换为路径。例如

    from pathlib import Path
    out_path = input('Enter the path to save the files')
    path = Path(out_path)
    

    import os
    out_path = input('Enter the path to save the files')
    path = os.path.normpath(out_path)
    

    answer 中阅读有关 str 到路径的更多信息

    另一种方法是使用像 Tkinter 这样的 GUI。例如

    from tkinter.filedialog import askdirectory
    path = askdirectory()
    

    获取路径后,可以将其添加到文件名中,如下所示

    filename = os.path.join(path,filename)
    

    打印进度可以用

    print(f'Now downloading {link} and saving as {filename}')
    

    编辑:os.path.normpath 中的变量名不正确

    【讨论】:

    • 我尝试将 import os out_path = input('输入保存文件的路径') path = os.path.normpath(p) 出现错误:import os out_path = input('输入保存文件的路径') path = os.path.normpath(p)
    • 对不起,我的错,它是os.path.normpath(out_path),也编辑了答案。谢谢
    • 我在添加您提供的内容后尝试了代码,我认为它正在运行,但存在无效参数 [ERRNO22]||输入保存文件的路径 C:\Users\User\Desktop\PTK Downloading: C:\Users\User\Desktop\PTK\10meg.test [Errno 22] Invalid argument: ' C:\\Users\\User\ \Desktop\\PTK\\10meg.test' 遇到未知错误。继续。正在下载:C:\Users\User\Desktop\PTK\50meg.test [Errno 22] 无效参数:'C:\\Users\\User\\Desktop\\PTK\\50meg.test' 遇到未知错误。继续。下载完毕。进程以退出代码 0 结束
    • 请检查并找出此处失败的行,即 urlretrieve 或 os.path.getsize。
    猜你喜欢
    • 2017-06-02
    • 1970-01-01
    • 1970-01-01
    • 2022-12-19
    • 2017-05-31
    • 2018-05-22
    • 2022-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多