Jacobm001
Jacobm001

Reputation: 4539

Saving a downloaded ZIP file w/Python

I'm working on a script that will automatically update an installed version of Calibre. Currently I have it downloading the latest portable version. I seem to be having trouble saving the zipfile. Currently my code is:

import urllib2
import re
import zipfile

#tell the user what is happening
print("Calibre is Updating")

#download the page
url = urllib2.urlopen ( "http://sourceforge.net/projects/calibre/files" ).read()

#determin current version
result = re.search('title="/[0-9.]*/([a-zA-Z\-]*-[0-9\.]*)', url).groups()[0][:-1]

#download file
download = "http://status.calibre-ebook.com/dist/portable/" + result
urllib2.urlopen( download )

#save
output = open('install.zip', 'w')
output.write(zipfile.ZipFile("install.zip", ""))
output.close()

Upvotes: 3

Views: 16140

Answers (4)

Arsenio Siani
Arsenio Siani

Reputation: 261

have you tryed

output = open('install.zip', 'wb') // note the "b" flag which means "binary file"

Upvotes: 2

Barosl Lee
Barosl Lee

Reputation: 176

There also can be a one-liner:

open('install.zip', 'wb').write(urllib.urlopen('http://status.calibre-ebook.com/dist/portable/' + result).read())

which doesn't have a good memory-efficiency, but still works.

Upvotes: 3

David Robinson
David Robinson

Reputation: 78600

You don't need to use zipfile.ZipFile for this (and the way you're using it, as well as urllib2.urlopen, has problems as well). Instead, you need to save the urlopen result in a variable, then read it and write that output to a .zip file. Try this code:

#download file
download = "http://status.calibre-ebook.com/dist/portable/" + result
request = urllib2.urlopen( download )

#save
output = open("install.zip", "w")
output.write(request.read())
output.close()

Upvotes: 7

miku
miku

Reputation: 188014

If you just want to download a file from the net, you can use urllib.urlretrieve:

Copy a network object denoted by a URL to a local file ...

Example using requests instead of urllib2:

import requests, re, urllib

print("Calibre is updating...")
content = requests.get("http://sourceforge.net/projects/calibre/files").content

# determine current version
v = re.search('title="/[0-9.]*/([a-zA-Z\-]*-[0-9\.]*)', content).groups()[0][:-1]
download_url = "http://status.calibre-ebook.com/dist/portable/{0}".format(v)

print("Downloading {0}".format(download_url))
urllib.urlretrieve(download_url, 'install.zip')
# file should be downloaded at this point

Upvotes: 2

Related Questions