python里有专门处理压缩文件的包zipfile,可以进行压缩、解压等各种常见操作,简要介绍,原文见Python zip模块。
ZIP
文件用zipfile.is_zipfile
判断。
import zipfile
print(zipfile.is_zipfile('samples/archive.zip'))
True
ZipFile
可以直接操作ZIP
,支持读取数据以及对其修改。
List
出来archive文件里内容,用namelist 和 infolist方法。返回list of filenames
或list of ZipInfo instances
。
import zipfile
zf = zipfile.ZipFile('samples/archive.zip','r')
# list filenames
for name in zf.namelist():
print name,
a.txt b.txt c.txt
# list file infomation
for info in zf.infolist():
print info.filename, info.date_time, info.file_size
a.txt (2016, 7, 15, 0, 5, 58) 2
b.txt (2016, 7, 15, 0, 6, 8) 2
c.txt (2016, 7, 15, 0, 6, 14) 2
read()
用read()
方法,以filename
作为参数,以string
形式返回数据。
zf = zipfile.ZipFile('samples/archive.zip')
for filename in zf.namelist():
# can use other than namelist,['there.txt','notthere.txt']
try:
data = zf.read(filename) # extract use read()
except KeyError:
print "Error: Did not find %s in zip file" % filename
else:
print filename, ':',
print repr(data)
a.txt : 'a\n'
b.txt : 'b\n'
c.txt : 'c\n'
extract()
zf = zipfile.ZipFile('samples/archive.zip','r')
# Extract a member from the archive to the current working directory
zf.extract('a.txt') # you may want to specify path param
# Extract all members from the archive to the current working directory
zf.extractall() # you may want to specify path param
创建新的zip
文件,只需要初始化一个新的ZipFile
即可,用w
模式,要添加数据,用write()
方法即可。
print('creating archive')
zf = zipfile.ZipFile('zipfile_write.zip',mode='w')
try:
print('adding readme.txt')
zf.write('readme.txt')
finally:
print('closing')
zf.close()
creating archive
adding readme.txt
closing
但是默认没有只是打包,没有压缩数据,如果压缩,需要用zlib
模块。默认压缩模式zipfile.ZIP_STORED
,可以改变为zipfile.ZIP_DEFLATED
。
# try to change compression type
try:
import zlib
compression = zipfile.ZIP_DEFLATED
except:
compression = zipfile.ZIP_STORED
modes = {zipfile.ZIP_DEFLATED: 'deflated', zipfile.ZIP_STORED: 'stored'}
print('creating archive')
zf = zipfile.ZipFile('zipfile_write_compression.zip',mode='w')
try:
print('adding README.txt with compression mode'+ str(modes[compression]))
zf.write('readme.txt',compress_type=compression)
finally:
print('closing')
zf.close()
creating archive
adding README.txt with compression modedeflated
closing