【问题标题】:Download file from URL and save it in a folder Python从 URL 下载文件并将其保存在 Python 文件夹中
【发布时间】:2019-11-18 22:00:42
【问题描述】:

我有很多文件类型为.docx 和.pdf 的URL 我想运行一个python 脚本,从URL 下载它们并将其保存在一个文件夹中。这是我为单个文件所做的,我会将它们添加到 for 循环中:

response = requests.get('http://wbesite.com/Motivation-Letter.docx')
with open("my_file.docx", 'wb') as f:
    f.write(response.content)

但它正在保存的my_file.docx 只有 266 个字节并且已损坏但 URL 很好。

更新:

添加了这段代码,它可以工作,但我想将它保存在一个新文件夹中。

import os
import shutil
import requests

def download_file(url, folder_name):
    local_filename = url.split('/')[-1]
    path = os.path.join("/{}/{}".format(folder_name, local_filename))
    with requests.get(url, stream=True) as r:
        with open(path, 'wb') as f:
            shutil.copyfileobj(r.raw, f)

    return local_filename

【问题讨论】:

标签: python python-requests


【解决方案1】:

尝试:

import urllib.request 
urllib.request.urlretrieve(url, filename)

【讨论】:

  • 值得注意的是,urlretrieve 是 Python 2 的遗留函数,可能会在某些时候被弃用。到目前为止还没有,但文档警告说它可能会。
【解决方案2】:

尝试使用stream 选项:

import os
import requests


def download(url: str, dest_folder: str):
    if not os.path.exists(dest_folder):
        os.makedirs(dest_folder)  # create folder if it does not exist

    filename = url.split('/')[-1].replace(" ", "_")  # be careful with file names
    file_path = os.path.join(dest_folder, filename)

    r = requests.get(url, stream=True)
    if r.ok:
        print("saving to", os.path.abspath(file_path))
        with open(file_path, 'wb') as f:
            for chunk in r.iter_content(chunk_size=1024 * 8):
                if chunk:
                    f.write(chunk)
                    f.flush()
                    os.fsync(f.fileno())
    else:  # HTTP status code 4XX/5XX
        print("Download failed: status code {}\n{}".format(r.status_code, r.text))


download("http://website.com/Motivation-Letter.docx", dest_folder="mydir")

请注意,上面示例中的mydir 是当前工作目录 中的文件夹名称。如果mydir 不存在,脚本将在当前工作目录中创建它并将文件保存在其中。您的用户必须有权在当前工作目录中创建目录和文件。

你可以在dest_folder中传递一个绝对文件路径,但要先检查权限。

P.S.:避免在一篇文章中提出多个问题

【讨论】:

  • 我在file_path中使用mac所以当我写r"\folder_name"它会创建一个文件名\folder_name"
  • 所以使用 os os.path.join('whereever', 'you', 'want', 'to', 'go') 或 pathlib: docs.python.org/3/library/pathlib.html 来正确处理路径。或者在您选择的操作系统路径样式中添加您自己的绝对路径。
  • 这个答案只是展示了一个使用请求处理文件下载的例子。当然你应该使用os包来处理文件文件系统)
  • @IvanVinogradov在我的问题的更新部分,当我运行它时,我得到No such file or directory:
  • 您需要新建一个文件夹并将文件保存在其中吗?
猜你喜欢
  • 2021-10-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-26
  • 2011-01-31
  • 1970-01-01
  • 1970-01-01
  • 2021-06-22
  • 1970-01-01
相关资源
最近更新 更多