如何使用python下载7z文件

时间:2018-07-05 12:43:16

标签: python python-3.x python-requests python-3.6

我要下载文件,可能是zip / 7z。当我使用以下代码时,它为7z文件提供了错误

import requests, zipfile, StringIO

zip_file_url = "http://www.blog.pythonlibrary.org/wp-content/uploads/2012/06/wxDbViewer.zip"
try:
 r = requests.get(zip_file_url, stream=True)
 z = zipfile.ZipFile(StringIO.StringIO(r.content))
except requests.exceptions.ConnectionError:
 print "Connection refused"

1 个答案:

答案 0 :(得分:0)

在请求文件时,只需确保HTTP状态代码为200,然后以二进制模式写出文件即可:

import os
import requests

URL = "http://www.blog.pythonlibrary.org/wp-content/uploads/2012/06/wxDbViewer.zip"
filename = os.path.basename(URL)

response = requests.get(URL, stream=True)

if response.status_code == 200:
    with open(filename, 'wb') as out:
        out.write(response.content)
else:
    print('Request failed: %d' % response.status_code)

如果请求成功,则下载的文件将出现在运行脚本的目录中,或者指示无法下载文件。