python常用模块-zipfile
# 处理.zip压缩文件,如果要操作的zip文件大小超过2G,应该将allowZip64设置为True。 import zipfile # ZipFile 读压缩文件case.zip的内容 zip_file1 = zipfile.ZipFile("D:\\case\\case.zip") # 加载压缩文件的内容,模式默认为"r" print(zip_file1) 结果: <zipfile.ZipFile filename='D:\\case\\case.zip' mode='r'> # 获取压缩文件case.zip的属性 zip_info = zip_file1.infolist() print(zip_info) 结果: [<ZipInfo filename='const.py' compress_type=deflate external_attr=0x20 file_size=8687 compress_size=2961>, <ZipInfo filename='auto.txt' compress_type=deflate external_attr=0x20 file_size=18 compress_size=23>] 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: 获取未压缩的文件大小 for i in zip_info: print(i.filename) print(i.file_size) print(i.header_offset) 结果: const.py 8687 0 auto.txt 18 2999 # namelist 读取压缩文件里面的文件 print(zip_file1.namelist()) 结果: ['const.py', 'auto.txt'] # 解压操作 方法1:zip_file1.extractall("D:\\case") 方法2: for file in zip_file1.namelist(): zipFile.extract(file, 'D:\\Work') zip_file1.close() # 关闭文件(操作后记得要关闭,不然会被python程序占用而无法释放) # 创建压缩文件test.zip zip_file2 = zipfile.ZipFile("D:\\case\\test.zip", "w") # 创建一个压缩文件,压缩文件名为test.zip,模式为"w" print(zip_file2) 结果: <zipfile.ZipFile filename='D:\\case\\test.zip' mode='w'> # 假设要把一个叫testdir中的文件全部添加到压缩包里(这里只添加一级子目录中的文件)(图片和txt文件不得行) zip_file2.write("D:\\test_zip\\1.docx", "D:\\test_zip\\2.docx") zip_file2.close() # 操作后记得要关闭,不然会被python程序占用而无法释放