我正在开发一个脚本,它会自动更新已安装的Calibre版本。目前我已经下载了最新的便携版本。我似乎无法保存zipfile。目前我的代码是:
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()
答案 0 :(得分:7)
您不需要使用zipfile.ZipFile
(而且您使用它的方式以及urllib2.urlopen
也存在问题)。相反,您需要将urlopen结果保存在变量中,然后read
并将该输出写入.zip文件。试试这段代码:
#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()
答案 1 :(得分:2)
如果您只想从网上下载文件,可以使用urllib.urlretrieve
:
将URL表示的网络对象复制到本地文件...
使用requests
代替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
答案 2 :(得分:2)
也可以有一个单行:
open('install.zip', 'wb').write(urllib.urlopen('http://status.calibre-ebook.com/dist/portable/' + result).read())
没有良好的记忆效率,但仍然有效。
答案 3 :(得分:1)
你试过吗
output = open('install.zip', 'wb') // note the "b" flag which means "binary file"