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/ ...
随机推荐
- Python基础篇(五)_文件和数据格式化
Python基础篇_文件和数据格式化 文件的使用:文件打开.关闭.读写 文件打开:通过open()函数打开文件,并返回一个操作文件的变量. 使用语法:<变量名> = (<文件路径以及 ...
- Leetcode_877. 石子游戏(区间dp)
偶数堆石子,只能从首尾取,取多的赢. 每次操作会产生两个子状态,区间dp,记得先枚举长度. code class Solution { public: int dp[505][505]; bool s ...
- Django-jwt token生成源码分析
一. 认证的发展历程简介 这里真的很简单的提一下认证的发展历程.以前大都是采用cookie.session的形式来进行客户端的认证,带来的结果就是在数据库上大量存储session导致数据库压力增大,大 ...
- C语言结构体实现类似C++的构造函数
其主要依靠函数指针来实现,具体看代码吧~ #include <stdio.h> #include <stdlib.h> #include <string.h> ty ...
- 第十六周Java实验作业
实验十六 线程技术 实验时间 2017-12-8 1.实验目的与要求 (1) 掌握线程概念: 多线程是进程执行过程中产生的多条执行线索,线程是比进程执行更小的单位. 线程不能独立存在,必须存在于进程 ...
- CTF_WriteUp_HTTP基本认证(Basic access authentication)
HTTP基本认证 在HTTP中,基本认证(英语:Basic access authentication)是允许http用户代理(如:网页浏览器)在请求时,提供用户名和密码 的一种方式.HTTP基本认证 ...
- springboot创建
1.点击File----->New----->Project... 2.输入MAVEN,组名.包名等相关参数 3.选择SpringBoot版本,选择项目需要依赖的相关骨架包 4.设置 ...
- spring5之容器始末源码赏析 (一)总览
首先,本系列并不是以介绍spring5 的新特性为主,之所以以spring5为标题,是因为即将赏析的源码来自最新的spring版本.虽说是spring最新版本,但是容器的整个生命周期与之前版本相比,并 ...
- ArrayList中的Iterator详解
每个实现Iterable接口的类必须提供一个iterator方法,返回一个Iterator对象,ArrayList也不例外 public Iterator<E> iterator() { ...
- 用一个例子说说gRPC的四种服务方法
本文通过一个简单的例子来演示这4种类型的使用方法 案例代码:https://github.com/codeAB/grpc-sample-example 目录结构说明 ├── calculator.pr ...