1

I want to download the file, it may be zip/7z. when I used the following code it is giving an error for the 7z file.

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"
Mukesh Bharsakle
  • 403
  • 1
  • 4
  • 17

1 Answers1

1

Just ensure the HTTP status code is 200 when requesting the file, and write out the file in binary mode:

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)

The downloaded file will then appear in the directory where the script is being run if the request was successful, or an indication the file could not be downloaded.

RoadRunner
  • 25,803
  • 6
  • 42
  • 75