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")
尝试使用stream选项:
注意上面例子中的
mydir
是当前工作目录中文件夹的名称。如果mydir
不存在,脚本将在当前工作目录中创建它并将文件保存在其中。用户必须具有在当前工作目录中创建目录和文件的权限。在您可以在
dest_folder
中传递绝对文件路径,但请先检查权限。在注意:避免在一篇文章中提出多个问题
尝试:
相关问题 更多 >
编程相关推荐