专栏首页技术沉淀Python: zipfile压缩解压文件

Python: zipfile压缩解压文件

判断是否是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:

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • Python: os模块实例详解

    用户2183996
  • Python: glob匹配文件

    用户2183996
  • 命令行工具:csvkit命令行操作csv

    用户2183996
  • Jupyter notebook - matlibplot配置

    1. 在jupyter notebook中用 matlibplot绘图,出现以下情况。

    riyusei
  • Leetcode 328. Odd Even Linked List

    版权声明:博客文章都是作者辛苦整理的,转载请注明出处,谢谢! https://blog.cs...

    Tyan
  • 剑指offer 合并两个排序的链表

    输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

    week
  • 本地存储之sessionStorage

      复制链接地址打开网页不会复制seessionStorage内的数据

    ProsperLee
  • awk工具

    叶瑾
  • Lua序列化方法

    lua序列化实现使用的是string.dump (),关于string.dump ()的介绍,lua的API文档中写到

    bering
  • 输入输出接口

    斯武丶风晴

扫码关注云+社区

领取腾讯云代金券