Python: zipfile压缩解压文件

开公众号啦,「心智万花筒」欢迎一起读书交流成长。


qr-code

判断是否是ZIP文件

zipfile.is_zipfile判断。

import zipfile
print(zipfile.is_zipfile('samples/archive.zip'))
True

ZipFile可以直接操作ZIP,支持读取数据以及对其修改。

读取文件信息

List出来archive文件里内容,用namelistinfolist方法。返回list of filenameslist 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

Ref:

  • Effbot
  • Python Module of the Week

你可能感兴趣的:(Python: zipfile压缩解压文件)