zf = zipfile.ZipFile('python.zip')
for filename in ['test.txt', 'notthere.txt']:
try:
info = zf.getinfo(filename)
except KeyError:
print 'ERROR: Did not find %s in zip file' % filename
else:
print "%s is %d bytes" % (info.filename, info.file_size)</pre><span style="color:#444444;font-family:georgia, times, 'times new roman', serif;font-size:13px;line-height:22px;background-color:#ffffff;"></span><span style="color:#444444;font-family:georgia, times, 'times new roman', serif;font-size:13px;line-height:22px;background-color:#ffffff;">如果需要查找的不存在ZIP文档里,会返回一个KeyError错误。</span><span style="color:#444444;font-family:georgia, times, 'times new roman', serif;font-size:13px;line-height:22px;background-color:#ffffff;"></span><pre class="brush:python;toolbar:false;">[root@www home]# python zipfile_getinfo.py
test.txt is 419430400 bytes
ERROR: Did not find notthere.txt in zip file3、从一个ZIP文档中提取文件
#!/usr/bin/env python
import zipfile
zf = zipfile.ZipFile('python.zip')
for filename in ['test.txt', 'notihere.txt']:
try:
data = zf.read(filename)
except KeyError:
print 'ERROR: Did not find %s in zip file' % filename
else:
print filename, ':'
print repr(data)
print</pre><strong style="margin:0px;padding:0px;border:0px;outline:0px;font-size:large;vertical-align:baseline;background-color:#ffffff;color:#444444;font-family:georgia, times, 'times new roman', serif;line-height:30px;"></strong><span style="color:#444444;font-family:georgia, times, 'times new roman', serif;font-size:13px;line-height:22px;background-color:#ffffff;">要提取的文件会被自动解压:</span><span style="color:#444444;font-family:georgia, times, 'times new roman', serif;font-size:13px;line-height:22px;background-color:#ffffff;"></span><pre class="brush:plain;toolbar:false;">[root@www home]# python zipfile_read.py
README.txt :
'The examples for the zipfile module use this file and example.zip as data.\n' ERROR: Did not find notthere.txt in zip file4、创建一个新的ZIP文件创建新的ZIP归档文件代码如下: