requests:如果文件不存在则下载
问题:
你想使用 requests python 库将 URL 下载到文件,但如果不存在你想跳过下载
解决方案
使用以下函数:
download_if_not_exists.py
import requests
import os.path
def download_file(filename, url):
"""
将 URL 下载到文件
"""
with open(filename, 'wb') as fout:
response = requests.get(url, stream=True)
response.raise_for_status()
# 将响应数据写入文件
for block in response.iter_content(4096):
fout.write(block)
def download_if_not_exists(filename, url):
"""
如果文件不存在,将 URL 下载到文件。
返回
-------
True 如果文件已下载,
False 如果它已存在
"""
if not os.path.exists(filename):
download_file(filename, url)
return True
return FalseCheck out similar posts by category:
Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow