Python zipfile 压缩和解压zip文件

zipfile 的使用

直接导入库:import zipfile

zipfile的常用函数ZipFile

 file 文件的含义:

1 如果是要压缩文件,这里就是要生成的文件路径和文件

2 如果要解压文件,这里要解压的文件

2 mode 看上图有四种类型

r 一般用在解压  表示读已经存在的文件

w 一般用在压缩文件 表示覆盖,

a 一般用在压缩文件 表示追加

x 一般用在压缩文件 表示排他,就是压缩的文件名存在会报错。

压缩文件

import zipfile
# 要压缩的文件路径
file_url = r"D:\test\hello.xlsx"
# 指定要压缩的文件路径和自己取的文件名
file_target = r"D:\test2\hello.zip"
# w 是覆盖的方法,如果创建的zip存在覆盖
zf = zipfile.ZipFile(file_target, mode="w")
# 这里注意没有arcname的话,压缩的文件会带路径注意名字最好跟压缩前的一样如果改为a.txt,这样的就把原来的压缩文件修改了
zf.write(file_url, arcname="hello.xlsx")
zf.close()

解压文件

import zipfile
# 要解压的文件路径
file_url = r"D:\test2\hello.zip"
# 指定解压后文件的路径
file_target = r"D:\test2"
# r 是默认值,可以省略
zf = zipfile.ZipFile(file_url)
zf.extractall(file_target)
zf.close()

压缩包内容信息查看

import zipfile

file_url = r"D:\test2\hello.zip"
zf = zipfile.ZipFile(file_url)
print(zf.namelist())  # 获取zip文档内所有文件的信息
print(zf.infolist())  # 获取zip文档内所有文件的名称列表
print(zf.printdir())  # 将zip文档内的信息打印到控制台上

其他的一些补充

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: 获取未压缩的文件大小。

猜你喜欢

转载自blog.csdn.net/qq_33210042/article/details/131659485