使用Python下载并解压缩文件 [英] Download and unzip file with Python

查看:213
本文介绍了使用Python下载并解压缩文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试下载并打开一个压缩文件,似乎在使用带有zipfile的文件类型句柄时遇到问题。我收到错误AttributeError:addinfourl实例没有属性seek运行时:

I am trying to download and open a zipped file and seem to be having trouble using a file type handle with zipfile. I'm getting the error "AttributeError: addinfourl instance has no attribute 'seek'" when running this:

import zipfile
import urllib2

def download(url,directory,name):
 webfile = urllib2.urlopen('http://www.sec.gov'+url)
 webfile2 = zipfile.ZipFile(webfile)
 content = zipfile.ZipFile.open(webfile2).read()
 localfile = open(directory+name, 'w')
 localfile.write(content)
 localfile.close()
 return()

download(link.get("href"),'./fails_data', link.text)


推荐答案

你不能在 urllib2 .urlopen ed文件。其支持的方法如下: http://docs.python.org/library/urllib.html# urllib.urlopen

You can't seek on a urllib2.urlopened file. The methods it supports are listed here: http://docs.python.org/library/urllib.html#urllib.urlopen.

您必须检索该文件(可能使用 urllib.urlretrieve http://docs.python.org/library/urllib.html#urllib.urlretrieve ),然后使用 zipfile

You'll have to retrieve the file (possibly with urllib.urlretrieve, http://docs.python.org/library/urllib.html#urllib.urlretrieve), then use zipfile on it.

或者,您可以 read() / code> urlopen ed文件,然后将其放入 StringIO 中,然后使用 zipfile ,如果你想要内存中的压缩数据。另请查看提取 extract_all 方法 zipfile if您只需要提取文件,而不是使用读取

Alternatively, you could read() the urlopened file, then put it into a StringIO, then use zipfile on that, if you wanted the zipped data in memory. Also check out the extract and extract_all methods of zipfile if you just want to extract the file, instead of using read.

这篇关于使用Python下载并解压缩文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆