从互联网上下载文件python代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| 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