【发布时间】: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
【问题讨论】:
-
Check this 你可能会在这里回答。
-
我认为@IvanVinogradov 回答了你的问题。
-
正确使用
os.path.join:path = os.path.join("/", folder_name, local_filename)