Python zipfile模块学习
转载自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模块学习的更多相关文章
- python - argparse 模块学习
python - argparse 模块学习 设置一个解析器 使用argparse的第一步就是创建一个解析器对象,并告诉它将会有些什么参数.那么当你的程序运行时,该解析器就可以用于处理命令行参数. 解 ...
- Python ZipFile模块详解(转)
Python zipfile模块用来做zip格式编码的压缩和解压缩的,zipfile里有两个非常重要的class, 分别是ZipFile和ZipInfo, 在绝大多数的情况下,我们只需要使用这两个cl ...
- python paramiko模块学习分享
python paramiko模块学习分享 paramiko是用python语言写的一个模块,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接.paramiko支持Linux, Sola ...
- Python logging 模块学习
logging example Level When it's used Numeric value DEBUG Detailed information, typically of interest ...
- Python time模块学习
Python time模块提供了一些用于管理时间和日期的C库函数,由于它绑定到底层C实现,因此一些细节会基于具体的平台. 一.壁挂钟时间 1.time() time模块的核心函数time(),它返回纪 ...
- python os模块学习
一.os模块概述 Python os模块包含普遍的操作系统功能.如果你希望你的程序能够与平台无关的话,这个模块是尤为重要的. 二.常用方法 1.os.name 输出字符串指示正在使用的平台.如果是wi ...
- python logging模块学习(转)
前言 日志是非常重要的,最近有接触到这个,所以系统的看一下Python这个模块的用法.本文即为Logging模块的用法简介,主要参考文章为Python官方文档,链接见参考列表. 另外,Python的H ...
- python atexit模块学习
python atexit模块 只定义了一个register模块用于注册程序退出时的回调函数,我们可以在这个函数中做一下资源清理的操作 注:如果程序是非正常crash,或者通过os._exit()退出 ...
- Python 第二模块学习总结
学习总结: 1.掌握对装饰器的用法 2.掌握生成器的用法 3.掌握迭代器的用法 4.熟悉Python内置函数 5.熟悉Python shutil/shelve/configparse/hashlib/ ...
随机推荐
- iview-admin里面的 axios 给包装了一层数据 libs/axios.js 数据做了一层拦截
interceptors (instance, url) { // 请求拦截 instance.interceptors.request.use(config => { // 添加全局的load ...
- JVM 参数及各部分含义(转)
转自:https://www.jianshu.com/p/1c6b5c2e95f9 JVM参数分类 JVM参数分为标准参数和非标准参数: 标准参数: "-"开头的参数,如-clie ...
- 如何使用Postman编写Testlink测试用例
Postman2Testlink 通过Postman快速操作testlink测试用例.测试套件.测试计划.添加关键词.添加自定义字段等等. 工具地址 https://github.com/liyinc ...
- F版本SpringCloud 2—什么是SpringCloud?SpringCloud版本选择
引言:搭建微服务架构就像是买电脑,使用SpringCloud就是在买品牌机. 前言 昂,美好的天气里,不想直接说技术,给小伙伴萌看看傍晚的天空吧. -- 能找到天上的北极星吗? 上一篇文章中,通过一个 ...
- Java中内部类和静态内部类的区别
内部类和静态内部类 示例 public class OuterClass { private int numPrivate = 1; public int numPublic = 2; public ...
- Python-String字符串操作
name='xioer-pipo' print(name.capitalize()) #第一个字符大写 print(name.expandtabs()) print(name.count('o')) ...
- Python实现一个ORM模型类
ORM是三个单词首字母组合而成,包含了Object(对象-类),Relations(关系),Mapping(映射).解释过字面意思,但ORM的概念仍然模糊.私以为要理解一个事物,最好的法子是搞明白它出 ...
- P5021 赛道修建 题解
原题链接 简要题意: 在一棵树上求 \(m\) 条不相交的路径的最小值的最大值. 本题部分分很多,而且本人也交了 \(27\) 次,所以一定要仔细讲部分分! 算法一 对于 \(b_i = a_i + ...
- [dp]牛牛与数组
时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32768K,其他语言65536K 64bit IO Format: %lld 题目描述 牛牛喜欢这样的数组: 1:长度为n 2:每一个 ...
- 采用vue编写的功能强大的swagger-ui页面
think-swagger-ui-vuele swagger-ui有非常多的版本,觉得不太好用,用postman,每个接口都要自己进行录入.所以在基于think-vuele进行了swagger格式js ...