我正在尝试下载并打开一个压缩文件,但似乎在使用带有 zipfile 的文件类型句柄时遇到问题。运行此命令时出现错误“AttributeError: addinfourl instance has no attribute '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)
最佳答案
总而言之,以下内容从网站检索压缩文件中第一个文件的内容:
import urllib
import zipfile
url = 'http://www.gutenberg.lib.md.us/4/8/8/2/48824/48824-8.zip'
filehandle, _ = urllib.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()
关于python - 使用 Python 下载并解压文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6861323/