【python】详解zipfile模块读取处理压缩文件实例

zipfile是python里用来做zip格式编码的压缩和解压缩的,由于是很常见的zip格式,所以这个模块使用频率也是比较高的。

zipfile模块常用的一些操作和方法:

一、is_zipfile(filename),测试filename的文件,看它是否是个有效的zipfile

In [1]: import zipfile

In [2]: zipfile.is_zipfile(r'C:\Users\BruceWong\.spyder-py3\test_file.zip')
Out[2]: True

二、ZipFile(filename[,mode[,compression[,allowZip64]]])

  • filename:文件对象;例如:’xxx.zip’
  • mode:可选r,w,a代表不同的打开文件的方式;r只读;w重写;a添加;
  • compression:指出这个zipfile用什么压缩方法,默认是ZIP_STORED,另一种选择是ZIP_DEFLATED;
  • allowZip64:是个bool型变量,当设置为True的时候就是说可以用来创建大小大于2G的zip文件,默认值是True;
In [3]: zipfile.ZipFile(r'C:\Users\BruceWong\.spyder-py3\test_file.zip','r')
Out[3]: <zipfile.ZipFile filename='C:\\Users\\BruceWong\\.spyder-py3\\test_file.zip' mode='r'>

1、z.close(),关闭文件,结束时必须要有

In [1]: import zipfile
In [2]: z = zipfile.ZipFile(r'C:\Users\BruceWong\.spyder-py3\test_file.zip','r')
In [3]: z.close()
In [4]: z
Out[4]: <zipfile.ZipFile [closed]>

2、z.extract(member, path=None, pwd=None),从zip中提取一个文件,member可以是namelist中的某个文件,也可以从z.infolist 中得到filename,将它放到指定的path下,pwd是密码,用于被加密的zip文件;如果path没有指定,比如在脚本ipython下运行,会提取保存在脚本默认根目录下,生成test_file文件,并提取出a.text文件保存在文件夹里;

In [11]: z.extract('test_file/a.txt', path=None, pwd=None)
Out[11]: 'C:\\Users\\BruceWong\\Documents\\test_file\\a.txt'

3、z.extractall(path[,pwd]),将所有文件按照namelist中显示得那样的目录结构从当前zip中提取出来并放到path下。//这两个extract的path若不存在都会自动创建出来的,且这个path必须是个目录,解压时一定是把一个文件,包含其相对zip包路径的所有目录一起解压出来。

In [12]: z.extractall()
In [13]: import os
#查询文件夹内容
In [14]: os.listdir(r'test_file')
Out[14]: ['a.txt', 'b.txt', 'c.txt', 'd.txt']

4、z.namelist(),返回一个列表,内容是zip文件中所有子文件的path(相对于zip文件包而言的)。相当于是一个保存了zip内部目录结构的列表

In [9]: z.namelist()
Out[9]:
['test_file/',
 'test_file/a.txt',
 'test_file/b.txt',
 'test_file/c.txt',
 'test_file/d.txt']

5、z.infolist(),返回一个列表,内容是每个zip文件中子文件的ZipInfo对象,这个对象有上文中提到的那些字段

In [10]: z.infolist()
Out[10]:
[<ZipInfo filename='test_file/' external_attr=0x10>,
 <ZipInfo filename='test_file/a.txt' compress_type=deflate external_attr=0x20 file_size=3 compress_size=5>,
 <ZipInfo filename='test_file/b.txt' compress_type=deflate external_attr=0x20 file_size=3 compress_size=5>,
 <ZipInfo filename='test_file/c.txt' compress_type=deflate external_attr=0x20 file_size=3 compress_size=5>,
 <ZipInfo filename='test_file/d.txt' compress_type=deflate external_attr=0x20 file_size=3 compress_size=5>]

6、z.printdir(),将zip文件的目录结构打印到stdout上,包括每个文件的path,修改时间和大小

In [15]: z.printdir()
File Name                                             Modified             Size
test_file/                                     2018-01-15 11:12:00            0
test_file/a.txt                                2018-01-15 11:12:18            3
test_file/b.txt                                2018-01-15 11:12:30            3
test_file/c.txt                                2018-01-15 11:12:42            3
test_file/d.txt                                2018-01-15 11:12:50            3

7、z.open(name[,mode[,pwd]]),获取一个子文件的文件对象,可以将其用来read,readline,write等等操作

In [16]: z.open('test_file/a.txt','r')
Out[16]: <zipfile.ZipExtFile name='test_file/a.txt' mode='r' compress_type=deflate>

In [17]: z.open('test_file/a.txt','r').read()
Out[17]: b'aaa'

8、z.setpassword(psw),可以为zip文件设置默认密码

9、z.testzip(),读取zip中的所有文件,验证他们的CRC校验和。返回第一个损坏文件的名称,如果所有文件都是完整的就返回None

In [23]: a = z.testzip()

In [24]: a

In [25]: a is None
Out[25]: True

10、z.write(filename[,arcname[,compression_type]]),将zip外的文件filename写入到名为arcname的子文件中(当然arcname也是带有相对zip包的路径的),compression_type指定了压缩格式,也是ZIP_STORED或ZIP_DEFLATED。z的打开方式一定要是w或者a才能顺利写入文件。

In [1]: import zipfile
#\\\\\\z的打开方式一定要是w或者a才能顺利写入文件//
In [2]: z = zipfile.ZipFile('out.zip','w')

In [3]: z.write('out.log')

In [4]: z.close()

11、简明使用解压缩文件代码:

  • 解压文件读取:
import zipfile

z = zipfile.ZipFile(filename, 'r') # 这里的第二个参数用r表示是读取zip文件,w是创建一个zip文件

for f in z.namelist():
    print(f)
  • 压缩进文件写入
import zipfile, os

z = zipfile.ZipFile(filename, 'w') # 注意这里的第二个参数是w,这里的filename是压缩包的名字

#假设要把一个叫testdir中的文件全部添加到压缩包里(这里只添加一级子目录中的文件):
if os.path.isdir(testdir):
    for d in os.listdir(testdir):
        z.write(testdir+os.sep+d)#os.sep是文件分隔符"//"
# close() 是必须调用的!
z.close()

于是我为了方便使用,创建了自已的一个 ZFile 类,主要是实现象 winrar 的右键菜单中的压缩到的功能–即将一个zip文件压缩到指定目录,自动创建相应的子目录。再有就是方便生成 zip 文件。类源码为:

import zipfile   
import os.path   
import os   

class ZFile(object):   
    def __init__(self, filename, mode='r', basedir=''):   
        self.filename = filename   
        self.mode = mode   
        if self.mode in ('w', 'a'):   
            self.zfile = zipfile.ZipFile(filename, self.mode, compression=zipfile.ZIP_DEFLATED)   
        else:   
            self.zfile = zipfile.ZipFile(filename, self.mode)   
        self.basedir = basedir   
        if not self.basedir:   
            self.basedir = os.path.dirname(filename)   

    def addfile(self, path, arcname=None):   
        path = path.replace('//', '/')   
        if not arcname:   
            if path.startswith(self.basedir):   
                arcname = path[len(self.basedir):]   
            else:   
                arcname = ''   
        self.zfile.write(path, arcname)   

    def addfiles(self, paths):   
        for path in paths:   
            if isinstance(path, tuple):   
                self.addfile(*path)   
            else:   
                self.addfile(path)   

    def close(self):   
        self.zfile.close()   

    def extract_to(self, path):   
        for p in self.zfile.namelist():   
            self.extract(p, path)   

    def extract(self, filename, path):   
        if not filename.endswith('/'):   
            f = os.path.join(path, filename)   
            dir = os.path.dirname(f)   
            if not os.path.exists(dir):   
                os.makedirs(dir)   
            self.zfile(f, 'wb').write(self.zfile.read(filename))   


def create(zfile, files):   
    z = ZFile(zfile, 'w')   
    z.addfiles(files)   
    z.close()   

def extract(zfile, path):   
    z = ZFile(zfile)   
    z.extract_to(path)   
    z.close()  
  • 13
    点赞
  • 98
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值