使用Python下载并解压缩文件

eri*_*rin 3 python download zipfile

我试图下载并打开一个压缩文件,似乎无法使用zipfile文件类型句柄.我在运行这个时遇到错误"AttributeError:addinfourl实例没有属性'seek'":

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)
Run Code Online (Sandbox Code Playgroud)

Mar*_*ius 6

综上所述,以下内容从网站检索压缩文件中的第一个文件的内容:

import urllib.request
import zipfile
    
url = 'http://www.gutenberg.lib.md.us/4/8/8/2/48824/48824-8.zip'
filehandle, _ = urllib.request.urlretrieve(url)
zip_file_object = zipfile.ZipFile(filehandle, 'r')
first_file = zip_file_object.namelist()[0]
file = zip_file_object.open(first_file)
content = file.read()
Run Code Online (Sandbox Code Playgroud)

  • 对于较新的 python 版本,请在第一行执行“import urllib.request as urllib”。 (2认同)

Ped*_*ito 6

从 2020 年开始,您可以使用dload下载并解压文件,即:

import dload
dload.save_unzip("https://file-examples.com/wp-content/uploads/2017/02/zip_2MB.zip")
Run Code Online (Sandbox Code Playgroud)

默认情况下,它会使用 zip 文件名提取到脚本路径上的目录,但您可以指定提取位置:

dload.save_unzip("https://file-examples.com/wp-content/uploads/2017/02/zip_2MB.zip", "/extract/here")
Run Code Online (Sandbox Code Playgroud)

安装使用pip install dload

  • 有人维护这个吗,自三月份以来我还没有看到任何提交? (2认同)
  • @Ari 似乎不是这样,这很不幸,因为它看起来像是一个非常酷的包。使用 `save_unzip` 时我也遇到了[此错误](https://github.com/x011/dload/issues/4) (2认同)

agf*_*agf 5

你不能在urllib2.urlopened文件上寻找.它支持的方法如下:http://docs.python.org/library/urllib.html#urllib.urlopen.

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

或者,您可以read()使用urlopened文件,然后将其放入a StringIO,然后使用zipfile它,如果您想要内存中的压缩数据.如果您只想提取文件而不是使用,请查看extractextract_all方法.zipfileread