Python实现压缩文件夹与解压缩zip文件的方法
作者:Hardy-Lee 时间:2023-07-31 20:43:09
本文实例讲述了Python实现压缩文件夹与解压缩zip文件的方法。分享给大家供大家参考,具体如下:
直接上代码
#coding=utf-8
#甄码农python代码
#使用zipfile做目录压缩,解压缩功能
import os,os.path
import zipfile
def zip_dir(dirname,zipfilename):
filelist = []
if os.path.isfile(dirname):
filelist.append(dirname)
else :
for root, dirs, files in os.walk(dirname):
for name in files:
filelist.append(os.path.join(root, name))
zf = zipfile.ZipFile(zipfilename, "w", zipfile.zlib.DEFLATED)
for tar in filelist:
arcname = tar[len(dirname):]
#print arcname
zf.write(tar,arcname)
zf.close()
def unzip_file(zipfilename, unziptodir):
if not os.path.exists(unziptodir): os.mkdir(unziptodir, 0777)
zfobj = zipfile.ZipFile(zipfilename)
for name in zfobj.namelist():
name = name.replace('\\','/')
if name.endswith('/'):
os.mkdir(os.path.join(unziptodir, name))
else:
ext_filename = os.path.join(unziptodir, name)
ext_dir= os.path.dirname(ext_filename)
if not os.path.exists(ext_dir) : os.mkdir(ext_dir,0777)
outfile = open(ext_filename, 'wb')
outfile.write(zfobj.read(name))
outfile.close()
if __name__ == '__main__':
zip_dir(r'E:/python/learning',r'E:/python/learning/zip.zip')
unzip_file(r'E:/python/learning/zip.zip',r'E:/python/learning2')
运行后在E:/python/learning目录下生成zip.zip压缩文件,同时在E:/python目录下解压缩zip.zip文件到learning2目录。
希望本文所述对大家Python程序设计有所帮助。
来源:https://blog.csdn.net/liyuan_669/article/details/25252683
标签:Python,压缩,zip
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
MSSQL存储过程学习笔记一 关于存储过程
2024-01-17 18:59:43
PyQt5实现QLineEdit添加clicked信号的方法
2021-02-08 18:24:02
FileSystem对象常用的文件操作函数有哪些?
2009-11-01 15:11:00
PyQT5速成教程之Qt Designer介绍与入门
2023-05-18 22:23:36
![](https://img.aspxhome.com/file/2023/7/131407_0s.jpg)
php 保留小数点
2023-06-21 10:47:04
vue项目部署到Apache服务器中遇到的问题解决
2024-05-22 10:42:36
![](https://img.aspxhome.com/file/2023/8/123218_0s.png)
java 使用poi 导入Excel数据到数据库的步骤
2024-01-19 11:21:34
![](https://img.aspxhome.com/file/2023/4/66684_0s.png)
Python 开发工具通过 agent 代理使用的方法
2022-10-19 05:15:31
利用python模拟实现POST请求提交图片的方法
2021-02-20 05:58:21
Python Selenium模块安装使用教程详解
2021-10-06 02:23:25
![](https://img.aspxhome.com/file/2023/2/134462_0s.png)
SQL Server默认1433端口修改方法
2010-07-22 22:35:00
![](https://img.aspxhome.com/file/UploadPic/20107/22/20090106201914465-93s.jpg)
如何快速地更新网页内容?
2010-01-01 15:12:00
Oracle如何设置表空间数据文件大小
2024-01-13 01:00:03
利用Python实现斐波那契数列的方法实例
2022-11-07 11:20:14
Python实现PS滤镜Fish lens图像扭曲效果示例
2022-02-01 05:25:02
![](https://img.aspxhome.com/file/2023/5/104935_0s.jpg)
python time模块用法实例详解
2023-10-09 18:12:50
HTML和CSS中的视觉语义
2010-07-09 13:08:00
![](https://img.aspxhome.com/file/UploadPic/20107/9/01-27s.jpg)
Python文件操作和数据格式详解(简单简洁)
2022-12-18 21:28:01
![](https://img.aspxhome.com/file/2023/9/99249_0s.png)
SQL Server错误代码大全及解释(留着备用)
2024-01-14 07:08:44
MySQL锁阻塞的深入分析
2024-01-20 12:47:22
![](https://img.aspxhome.com/file/2023/4/71104_0s.png)