Python使用zipfile模块压缩目录(包含空目录)、压缩文件、解压文件
2023-09-11 14:21:07 时间
主要功能:压缩目录、压缩文件、解压文件
import os import zipfile # 压缩目录、或文件 def zip(srcPath=None, zipFilePath=None, includeDirInZip=True): if not zipFilePath: zipFilePath = srcPath + ".zip" parentDir, dirToZip = os.path.split(srcPath) # zipfile.write的第2个参数需要为相对路径,所以需要转换 def trimPath(path): # 获取目录名称,前面带有\ archivePath = path.replace(parentDir, "", 1) if parentDir: # 去掉第一个字符 archivePath = archivePath.replace(os.path.sep, "", 1) if not includeDirInZip: archivePath = archivePath.replace(dirToZip + os.path.sep, "", 1) return archivePath outFile = zipfile.ZipFile(zipFilePath, "w", compression=zipfile.ZIP_DEFLATED) if os.path.isdir(srcPath): # 目录的压缩包 for (archiveDirPath, dirNames, fileNames) in os.walk(srcPath): for fileName in fileNames: filePath = os.path.join(archiveDirPath, fileName) # write的第2个参数需要为相对路径 outFile.write(filePath, trimPath(filePath)) # 包含空目录 if not fileNames and not dirNames: zipInfo = zipfile.ZipInfo(trimPath(archiveDirPath) + "/") outFile.writestr(zipInfo, "") else: # 文件的压缩包 outFile.write(srcPath, trimPath(srcPath)) outFile.close() # 解压文件 def unzip(zipFilePath, savePath=None): r = zipfile.is_zipfile(zipFilePath) if r: if not savePath: savePath = os.path.split(zipFilePath)[0] fz = zipfile.ZipFile(zipFilePath, 'r') for file in fz.namelist(): fz.extract(file, savePath) else: print('不是一个zip文件') if __name__ == '__main__': zip(r"D:\testZip") unzip(r'D:\testZip.zip')
压缩目录代码来自:https://www.cnblogs.com/staff/p/16290689.html,除此之外,增加了压缩文件,解压文件。
相关文章
- python设计模式之常用创建模式总结(二)
- Python工作日类库Busines Holiday介绍
- Eclipse Kepler SR2 + Python 3.4 + JDK7+Pydev3.4 搭建 python 开发环境(MAC)
- Python 代码性能优化技巧
- python多进程中apply和apply_async用法详解
- python模块——hashlib模块(简单文件摘要算法实现)
- python shutil 文件操作模块
- 《python 与数据挖掘 》一1.3 Python开发环境的搭建
- Python 字符串小节
- 【Python】【PyPI】twine模块打包python项目上传pypi
- 【python】+704个常用工具Python库
- python做中学(八)匿名函数lambda的用法
- hdf 5文件格式及python中利用h5py模块读写h5文件
- python pip 安装库文件报错:pip install ImportError: No module named _internal
- python模块之imghdr(识别不同格式的图片文件)
- python之模块csv之CSV文件的写入(基本结构)
- python之模块csv之CSV文件的写入(按行写入)
- python学习之OpenCV-Python模块的部分应用示例(生成素描图和动漫图)
- 使用 Python 实现电梯调度的核心算法【100010451】
- 基于Python+MySQL实现(Web)学生成绩管理系统【100010288】
- Python 网络教程大全之 05 如何获取url下载文件的大小?
- 【Python】文件操作
- Python 基础 之 Ubuntu 上安装 python 和 python-pip
- Python 基础 之 python 中 进程、线程、协程对比 区别和联系
- Unity 工具 之 报错 Jenkins 执行/调用 Python 脚本,报错提示 ‘python‘ 不是内部或外部命令,也不是可运行的程序或批处理文件
- python读写Excel文件(xlrd、xlwr)
- python中的函数与文件操作
- python基础学习:使用os模块批量移动文件
- 【Linux学习笔记】解决:yum install python-dev 报错(CentOS安装Python-dev库)
- Python 修改图片文件的名称为拍摄时间
- python将h264文件视频转为mp4格式