python使用zipfile递归压缩和解压缩文件
2024-10-09 13:52:07
import shutil,zipfile,os
class ToolModel(object): def dfs_get_zip_file(self,input_path, result, ignore=[]):
'''
递归目录
:param input_path: 输入路径
:param result: 列表
:param ignore: 忽略文件或目录名
:return:
'''
files = os.listdir(input_path)
for file in files:
filePath = input_path + '/' + file
if file in ignore:
continue
if os.path.isdir(filePath):
self.dfs_get_zip_file(filePath, result, ignore)
else:
result.append(filePath) def zip_path(self,input_path, output_path, ignore=[]):
'''
:param input_path: 输入路径 /app/adminkit
:param output_path: 输出路径 /app/adminkit.zip
:param ignore: 忽略文件或目录名
:return:
'''
outdir = os.path.dirname(output_path)
if not os.path.isdir(outdir):
os.makedirs(outdir)
f = zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED)
filelists = []
self.dfs_get_zip_file(input_path, filelists, ignore)
for file in filelists:
file = file.replace('\\', '/')
input_path = input_path.replace('\\', '/')
f.write(file, file.replace(input_path, ''))
f.close()
return output_path def unzip(self,filename: str,dirname):
'''
解压缩
:param filename: 压缩文件名
:param dirname: 解压缩输出目录
:return:
'''
try:
file = zipfile.ZipFile(filename)
file.extractall(dirname)
file.close()
# 递归修复编码
self.rename(dirname)
except:
print(f'{filename} unzip fail') def rename(self,pwd: str, filename=''):
"""压缩包内部文件有中文名, 解压后出现乱码,进行恢复""" path = f'{pwd}/{filename}'
if os.path.isdir(path):
for i in os.scandir(path):
self.rename(path, i.name)
newname = filename.encode('cp437').decode('gbk')
os.rename(path, f'{pwd}/{newname}') def del_file(self,filepath):
"""
删除指定路径下的所有文件和文件夹
:param filepath: 路径
:return:
"""
del_list = os.listdir(filepath)
for f in del_list:
file_path = os.path.join(filepath, f)
if os.path.isfile(file_path):
os.remove(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
最新文章
- Spring MVC 处理静态资源不能访问问题
- CentOS 6.5安装在VMWare中Bridge模式下网卡eth0不能自动激活的问题
- apache和tomcat有什么不同,为什么要整合apache 和tomcat?
- informix dbaccess 常用执行方式及常见技巧
- 从零开始学习Node.js例子三 图片上传和显示
- Windows7 IIS7.5 HTTP Error 503 The service is unavailable 另类解决方案
- Android画柱状图,圆形图和折线图的demo
- yum 安装 PHP,apache,nginx,mysql
- HttpURLConnection访问url的工具类
- 何谓Dandy?它是一种着装风格
- Codeforces 442B Andrey and Problem(贪婪)
- documentsUI源码分析
- Hibernate学习笔记(3)---hibernate关联关系映射
- ZooKeeper:win7上安装单机及伪分布式安装
- servlet3.0 新特性——异步处理
- ppt制作元素采集
- reduce函数
- centos7的启动流程
- MYSQL的常用函数(字符串函数)
- Grid++Report
热门文章
- C#数据结构与算法系列(二十三):归并排序算法(MergeSort)
- 3.OSPF协议及链路状态算法
- C++语法小记---函数模板
- 【Floyd算法+贪心】 travel 计蒜客 - 45275
- git安装并与远程仓库关联相关配置
- ajax异步上传图片&;SpringMVC后台代码
- select、poll和epoll之间的区别
- 附025.kubeadm部署Kubernetes更新证书
- Laravel 使用阿里云 oss 存储对象
- [Abp vNext 源码分析] - 23. 二进制大对象系统(BLOB)