【问题标题】:How do I download a file from a website in python without the users username?python - 如何在没有用户名的情况下从python网站下载文件?
【发布时间】:2022-01-04 06:59:20
【问题描述】:

所以我正在尝试制作一个下载工具来通过链接下载东西,这是我的代码中的一个 sn-p

if download_choice == "14":
        print("Downloading test file to Desktop...")
        myfile14 = requests.get(url14)
        open('c:/users/%userprofile%/desktop/', 'wb').write(myfile14.content)

我想制作一个可以通过链接下载东西的程序。我希望它不仅可以在我的所有 PC 上运行。这是错误:

Traceback (most recent call last): File "C:\Users\David\Desktop\Windows Download Tool\Python\WDT.py", line 100, in <module> open('c:/users/%userprofile%/desktop/', 'wb').write(myfile14.content) FileNotFoundError: [Errno 2] No such file or directory: 'c:/users/%userprofile%/desktop/'

【问题讨论】:

  • @lema 这究竟是如何解决他的问题的?
  • @lema no i didn't.
  • 重点是:真正的问题是什么?这段代码有什么问题(就结果而言)?你能指望什么?你的问题应该更准确
  • 请提供更多信息
  • @Christophe 我想制作一个可以通过链接下载东西的程序。我希望它不仅可以在我的所有 PC 上运行。这是错误回溯(最近一次调用最后一次):文件“C:\Users\David\Desktop\Windows 下载工具\Python\WDT.py”,第 100 行,在 open('c:/users/% userprofile%/desktop/', 'wb').write(myfile14.content) FileNotFoundError: [Errno 2] No such file or directory: 'c:/users/%userprofile%/desktop/'

标签: python python-requests


【解决方案1】:

Python 不使用%userprofile% 来获取执行用户的用户名。

为此,您需要导入包os 并运行它的getlogin 函数。这将返回一个带有当前用户名的字符串

例子:

import os

username = os.getlogin()
if download_choice == "14":
    print("Downloading test file to Desktop...")
    myfile14 = requests.get(url14)
    open(f'C:/Users/{username}/desktop/', 'wb').write(myfile14.content)

我使用 f-string 来打开文件,因为它是 PEP-8 的首选(它只是正确的代码样式)

注意:这只适用于windows机器

【讨论】:

    猜你喜欢
    • 2019-05-09
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 2020-09-12
    • 1970-01-01
    • 2019-07-04
    • 2023-03-14
    • 2020-07-31
    相关资源
    最近更新 更多