#!/usr/bin/python
#coding:utf-8
'''
author:huhaicool@sina.com
date 2015-09-06
version 1.0
python 3.x
'''
import os,os.path
import zipfile
def zip_dir(file_path,zfile_path):
'''
function:压缩
params:
file_path:要压缩的件路径,可以是文件夹
zfile_path:解压缩路径
description:可以在python2执行
'''
filelist = []
if os.path.isfile(file_path):
filelist.append(file_path)
else :
for root, dirs, files in os.walk(file_path):
for name in files:
filelist.append(os.path.join(root, name))
print('joined:',os.path.join(root, name),dirs)
zf = zipfile.ZipFile(zfile_path, "w", zipfile.zlib.DEFLATED)
for tar in filelist:
arcname = tar[len(file_path):]
print(arcname,tar)
zf.write(tar,arcname)
zf.close()
def unzip_file(zfile_path, unzip_dir):
'''
function:解压
params:
zfile_path:压缩文件路径
unzip_dir:解压缩路径
description:
'''
try:
with zipfile.ZipFile(zfile_path) as zfile:
zfile.extractall(path=unzip_dir)
except zipfile.BadZipFile as e:
print (zfile_path+" is a bad zip file ,please check!")
if __name__ == '__main__':
#zip_dir(r'/tmp/xungou',r'/tmp/xungou.zip')
unzip_file(r'/tmp/xungou.zip',r'/tmp/xungou')
Python3zip压缩解压简单使用
最新推荐文章于 2024-09-12 10:00:00 发布