python中的zipfile用法

介绍

zipfile是一个用来压缩文件和解压缩文件的模块,它有两个常用的类,分别是ZipFile和ZipInfo。
其中ZipFile是主要的类,用来创建和读取zip文件,而ZipInfo是存储的zip文件的每个文件的信息的。

如果我们想要压缩或解压缩,首先要实例化一个 ZipFile 对象。ZipFile 的构造方法有两个参数,第一个参数是必选参数,接受一个字符串格式的压缩包名称,第二个参数为可选参数,表示打开模式,类似于文件操作,有r/w/a三种模式,分别代表读、写、添加,默认为r,即读模式。压缩使用w,解压缩使用r。

压缩

创建一个zip文件对象,压缩是需要把mode改为‘w’

zfile=zipfile.ZipFile("test.zip","w")

将文件写入zip文件中,即将文件压缩

zfile.write(r"../test.py")

将zip文件对象关闭

zfile.close()

解压

zfile=zipfile.ZipFile("../test.zip","r")

zfile.extractall()

ZipFile相关方法及属性

ZipFile.getinfo(name) 方法返回的是一个ZipInfo对象,表示zip文档中相应文件的信息。它支持如下属性:

ZipInfo.filename: 获取文件名称。

ZipInfo.date_time: 获取文件最后修改时间。返回一个包含6个元素的元组:(年, 月, 日, 时, 分, 秒)

ZipInfo.compress_type: 压缩类型。

ZipInfo.comment: 文档说明。

ZipInfo.extr: 扩展项数据。

ZipInfo.create_system: 获取创建该zip文档的系统。

ZipInfo.create_version: 获取 创建zip文档的PKZIP版本。

ZipInfo.extract_version: 获取 解压zip文档所需的PKZIP版本。

ZipInfo.reserved: 预留字段,当前实现总是返回0。

ZipInfo.flag_bits: zip标志位。

ZipInfo.volume: 文件头的卷标。

ZipInfo.internal_attr: 内部属性。

ZipInfo.external_attr: 外部属性。

ZipInfo.header_offset: 文件头偏移位。

ZipInfo.CRC: 未压缩文件的CRC-32。

ZipInfo.compress_size: 获取压缩后的大小。

ZipInfo.file_size: 获取未压缩的文件大小。

解压含密码的压缩文件

import zipfile #导入模块,它是做压缩和解压缩的

password="123" #我们设定的口令

zfile = zipfile.ZipFile("test.zip") #要解压缩的压缩包

zfile.extractall(path='C:\Users\Administrator\Desktop\', members=zfile.namelist(), pwd=password.encode('utf-8'))

# 进行解压缩操作,path为输出的路径

参考

https://www.cnblogs.com/wangylblog/p/13925894.html
https://blog.csdn.net/qq_33485434/article/details/82253642