转载自https://www.j4ml.com/t/15270

import zipfile
import os
from zipfile import ZipFile class ZipManage(ZipFile): def check(self, Name):
# 检查 文件指针是否有效
if self.fp == '':
raise RuntimeError('ZIP archive is closed')
# 检查 文件是否用 append 模式打开
if self.mode != 'a':
raise RuntimeError('ZIP archive Requires appended("a") mode to open')
# 检查 文件或文件夹 是否在zip中
is_existed = False
for FileName in self.filelist:
if FileName.filename.startswith(Name):
is_existed = True;
break; if is_existed == False:
raise RuntimeError('ZIP archive not found ', Name) # 删除zip包中的文件
def remove(self, szFileName):
self.check(szFileName) # 获取 要删除文件在zip中的信息
fileinfo = self.getinfo(szFileName)
print(type(fileinfo)) headerOffSet = fileinfo.header_offset
fileBlockLen = len(fileinfo.FileHeader()) + fileinfo.compress_size # 根据要删除的文件信息, 更新zip包中其他文件的头部偏移值
for info in self.infolist():
if info.header_offset >= (headerOffSet + fileBlockLen):
info.header_offset -= fileBlockLen # 将文件指针移动到 待删除文件的末尾
self.fp.seek(headerOffSet + fileBlockLen) # 读取 zip中 待删除文件后 的全部数据
data = self.fp.read() # 移动文件指针到 待删除文件的开始
self.fp.seek(headerOffSet) # 覆写数据
self.fp.write(data) # 截断文件
self.fp.truncate() # 更新 zip 中的文件索引信息
self._didModify = True
self.filelist.remove(fileinfo)
del self.NameToInfo[fileinfo.filename] # 删除 zip 中文件夹
def remove_dir(self, szDirName):
self.check(szDirName) # 获取 要删除文件夹在zip中的信息
dirInfo = self.getinfo(szDirName) # 获取 头部信息 和 文件块的大小
headerOffSet = dirInfo.header_offset
fileBlockLen = 0
for file in self.infolist():
if file.filename.startswith(szDirName):
fileBlockLen += (len(file.FileHeader()) + file.compress_size) for file_head_info in self.infolist():
if file_head_info.header_offset >= (headerOffSet + fileBlockLen):
file_head_info.header_offset -= fileBlockLen # 将文件指针移动到 待删除文件的末尾
self.fp.seek(headerOffSet + fileBlockLen) # 读取 zip中 待删除文件后 的全部数据
latedata = self.fp.read() # 移动文件指针到 待删除文件的开始
self.fp.seek(headerOffSet) # 覆写数据
self.fp.write(latedata) # 截断文件
self.fp.truncate() # 更新 zip 中的文件索引信息
self._didModify = True # 反向迭代删除
for i in range(len(self.infolist())-1, -1, -1):
info = self.infolist()[i]
if info.filename.startswith(szDirName):
self.filelist.remove(info)
del self.NameToInfo[info.filename] # 替换 zip 文件中的信息
def replace(self, szReplaceFilename, szNewFilePath):
self.check(szReplaceFilename) if not os.path.exists(szNewFilePath):
print(szNewFilePath,' is not existed')
return; fileinfo = self.getinfo(szReplaceFilename)
self.remove(szReplaceFilename)
self.write(szNewFilePath,fileinfo.filename,fileinfo.compress_type) def test_remove():
file = ZipManage('/home/s/Desktop/1.zip', 'a')
file.remove('1/1/2/22/test.txt') def test_remove_dir():
file = ZipManage('/home/s/Desktop/1.zip', 'a')
file.remove_dir('1/1/2/22/') def test_replace():
file = ZipManage('/home/s/Desktop/1.zip', 'a')
file.replace('1/1/test.txt', '/home/s/Desktop/test.txt')

Python zipfile模块学习的更多相关文章

  1. python - argparse 模块学习

    python - argparse 模块学习 设置一个解析器 使用argparse的第一步就是创建一个解析器对象,并告诉它将会有些什么参数.那么当你的程序运行时,该解析器就可以用于处理命令行参数. 解 ...

  2. Python ZipFile模块详解(转)

    Python zipfile模块用来做zip格式编码的压缩和解压缩的,zipfile里有两个非常重要的class, 分别是ZipFile和ZipInfo, 在绝大多数的情况下,我们只需要使用这两个cl ...

  3. python paramiko模块学习分享

    python paramiko模块学习分享 paramiko是用python语言写的一个模块,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接.paramiko支持Linux, Sola ...

  4. Python logging 模块学习

    logging example Level When it's used Numeric value DEBUG Detailed information, typically of interest ...

  5. Python time模块学习

    Python time模块提供了一些用于管理时间和日期的C库函数,由于它绑定到底层C实现,因此一些细节会基于具体的平台. 一.壁挂钟时间 1.time() time模块的核心函数time(),它返回纪 ...

  6. python os模块学习

    一.os模块概述 Python os模块包含普遍的操作系统功能.如果你希望你的程序能够与平台无关的话,这个模块是尤为重要的. 二.常用方法 1.os.name 输出字符串指示正在使用的平台.如果是wi ...

  7. python logging模块学习(转)

    前言 日志是非常重要的,最近有接触到这个,所以系统的看一下Python这个模块的用法.本文即为Logging模块的用法简介,主要参考文章为Python官方文档,链接见参考列表. 另外,Python的H ...

  8. python atexit模块学习

    python atexit模块 只定义了一个register模块用于注册程序退出时的回调函数,我们可以在这个函数中做一下资源清理的操作 注:如果程序是非正常crash,或者通过os._exit()退出 ...

  9. Python 第二模块学习总结

    学习总结: 1.掌握对装饰器的用法 2.掌握生成器的用法 3.掌握迭代器的用法 4.熟悉Python内置函数 5.熟悉Python shutil/shelve/configparse/hashlib/ ...

随机推荐

  1. Python基础篇_实例练习(二)

    问题1:假设有同学A,A每周在工作日进步,周末退步,问一年(365天)后A同学是一年前的几倍? 工作日进步由用户输入,周末下降0.01即1% deyup = eval(input()) deyfact ...

  2. JAVA-迭代器\增强型for循环。(新手)

    //导入的包.import java.lang.reflect.Array;import java.util.*;//创建的一个类.public class zylx1 { //公共静态的主方法. p ...

  3. Python3学习之路~10.3 论事件驱动与异步IO

    论事件驱动----详见:https://www.cnblogs.com/alex3714/articles/5248247.html Select\Poll\Epoll异步IO----详见:http: ...

  4. 4L-线性表之数组

    关注公众号 MageByte,设置星标点「在看」是我们创造好文的动力.后台回复 "加群" 进入技术交流群获更多技术成长. 数组对于每一门编程语言来说都是重要的数据结构之一,当然不同 ...

  5. iOS/macOS推荐个高效苹果开发工具, JSON 转模型代码工具,不再为复杂JSON数据写模型而烦恼,支持Swift/Objective-C,极速转换

    CCJSON 是一款运行在macOS上 JSON 转模型代码工具,不再为复杂JSON数据写模型而烦恼,可识别嵌套模型,字典/数组,支持Swift/Objective-C,操作方便,极速转换.下载 效果 ...

  6. Mol Cell Proteomics. | MARMoSET – Extracting Publication-ready Mass Spectrometry Metadata from RAW Files

    本文是马克思普朗克心肺研究所的三名研究者Marina Kiweler.Mario Looso和Johannes Graumann发表在8月刊的MCP的一篇文章. 由于Omics实验经常涉及数百个数据文 ...

  7. 【攻防世界】simple-unpack

    知识:upx脱壳 simple-unpack 难度系数: 3.0 题目来源: 暂无 题目描述:菜鸡拿到了一个被加壳的二进制文件 提示说有壳子:然后用PE分析发现是ELF upx的壳子

  8. 解决python3使用cx_Freeze打包成exe后不能运行

    我使用的是python3.4,在使用cx_Freeze打包成exe后发现有些打包后程序能够运行,但是有些无法运行 这是控制台报错 经过多方查找发现原来是windows缺少一些python的扩展包 如下 ...

  9. Building Applications with Force.com and VisualForce (DEV401) 中用到的Recruiting Application介绍

    1.Who uses Recruiting Application. 2. Recruiting Application Object Model

  10. PHP7内核(八):深入理解字符串的实现

    在前面大致预览了常用变量的结构之后,我们今天来仔细的剖析一下字符串的具体实现. 一.字符串的结构 struct _zend_string { zend_refcounted_h gc; /* 字符串类 ...