【问题标题】:How to download 7z file using python如何使用python下载7z文件
【发布时间】:2018-07-05 12:43:16
【问题描述】:

我想下载文件,可能是 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"

【问题讨论】:

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


【解决方案1】:

请求文件时确保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)

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

【讨论】:

    猜你喜欢
    • 2021-12-29
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-23
    • 2019-12-13
    • 2018-08-13
    • 2021-09-25
    相关资源
    最近更新 更多