从URL下载文件并将其保存在Python文件夹中

2024-09-30 14:15:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有很多文件类型为.docx和{}的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没有问题。在

更新:

添加了这个代码,它工作,但我想保存在一个新的文件夹。在

^{pr2}$

Tags: 文件脚本文件夹comhttpurlforget
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中传递绝对文件路径,但请先检查权限。在

注意:避免在一篇文章中提出多个问题

尝试:

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

相关问题 更多 >

    热门问题