import requests
import traceback
import os
def download_file(url, filename):
"""将链接中的数据存储入文件中。
Args:
url: 链接。
filename: 文件路径名。
Raises:
KeyboardInterrupt: 用户按^C引发异常。
Exception: 发生异常。
"""
if os.path.exists(filename):
print('file '+filename+' exists!')
return
try:
r = requests.get(url, stream=True, timeout=60)
r.raise_for_status() # 建立连接
with open(filename, 'wb') as f:
for chunk in r.iter_content(chunk_size=1024): # 分块写入二进制内容
if chunk:
f.write(chunk)
f.flush()
print('downloading '+filename+' successfully!')
return filename
except KeyboardInterrupt:
if os.path.exists(filename):
os.remove(filename)
raise KeyboardInterrupt
except Exception:
traceback.print_exc()
if os.path.exists(filename):
os.remove(filename)
创建于2412251740,修改于2412251740
标签:exists,python,代码,filename,print,import,os,chunk,下载 From: https://www.cnblogs.com/tellw/p/18631083