转载自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. vue中v-slot使用

    vue中v-slot使用 1,v-slot的使用步骤 <!-- slot.vue--> <!-- 通过name属性指定具名插槽,没有name属性的为默认插槽--> <sl ...

  2. SpringCloud系列之配置中心(Config)使用说明

    大家好,最近公司新项目采用SpingCloud全家桶进行开发,原先对SpringCloud仅仅只是停留在了解的初级层面,此次借助新项目的契机可以深入实践下SpringCloud,甚是Happy.大学毕 ...

  3. LeetCode--179场周赛题解

    水题: class Solution { public: string generateTheString(int n) { string s; string a="a",b=&q ...

  4. Drawing Simple Polygon(Create Simple Polygon from unordered points by angle sorting)

    Keywords: 极角排序, Simple Polygon Generation Given set of points in the plane, your task is to draw a p ...

  5. JDK14的新特性-Switch新功能

    2020年3月17日,Oracle正式发布了JDK14版本,共新增了16项新特性 本文重点写一下关于switch的新功能: switch 表达式扩展了 switch 语句,使其不仅可以作为语句(sta ...

  6. cmdb 配置

    cmdb客户端文件夹创建 客户端:client:-bin:启动文件-src:源文件(核心代码)-conf:配置文件-lib:全局的一些方法 和配置-test:测试文件

  7. P5663 加工零件 题解

    原题链接 简要题意: 给定一个图,每次询问从 \(x\) 节点开始,\(y\) 步能不能达到 \(1\) 号节点. 算法一 这也是我本人考场算法.就是 深搜 . 因为你会发现,如果 \(x\) 用 \ ...

  8. 洛谷P1003 铺地毯 模拟

    这一题就是一个很普通的模拟,每次输入的时候存储四个角的值 把四个角的横纵坐标存储在一排.然后在倒序遍历一遍,查找的时候就看所要查找的坐标在不在这个范围内,如果找到了就标记一下再输出,如果没有找到就输出 ...

  9. 关于js中iframe 中 location.href的用法

    关于js中"window.location.href"."location.href"."parent.location.href".&qu ...

  10. PHP7内核(一):发展史

    PHP1 1994年,一位名叫Rasmus lerdorf的兄台为了在网上展示自己的履历和网页流量的统计,用Perl开发了一套脚本,后来因与日俱增的需求无法得到满足,lerdorf便使用c语言进行了重 ...