Python实现多级目录压缩与解压文件的方法

yipeiwu_com5年前Python基础

本文实例讲述了Python实现多级目录压缩与解压文件的方法。分享给大家供大家参考,具体如下:

咱向来就是拿来主意,也发个东西供同行“拿来”使用吧

咱信奉的就是少量的代码完成大量的工作,虽然代码不多,但还是要用大脑的。发出来供大家参考

功能:

  • 支持中文路径,支持多级目录
  • 支持跨平台,在linux和window下都可直接使用
  • 压缩的多态性
    • 压缩包不带级父文件夹目录压缩
    • 压缩包带父级文件夹目录
    • 不指定目标文件与路径压缩
    • 指定压缩包名称不指定路径压缩

还是看代码吧

#coding:utf-8
#压缩解压文件模块
#支持中文路径,支持多级目录
#支持跨平台,在linux和window下都可直接使用
#python 2.7.2
#author:xieShuxu
#QQ:258356793
#Email:sondx@qq.com
import zipfile,os
class ZipException(Exception):
    pass
def unZipFile(zipPath,unZipPath=''):
    '''解压文件
    zipPath 要解压的文件路径
    unZipPath 解压目标路径 默认解压到zipPath所在目录
    '''
    try:
        filePath=filePath.decode('utf-8');
        zipFilePath=zipFilePath.decode('utf-8');
    except:
        print '================'
    if not os.path.exists(zipPath):
        raise ZipException,'function unZipFile:not exists file or dir(%s)' %zipPath;
    if unZipPath=='':
        unZipPath=os.path.splitext(zipPath)[0];
    if not unZipPath.endswith(os.sep):
        unZipPath+=os.sep;
    z = zipfile.ZipFile(zipPath, 'r')
    #zipInfolist=z.namelist();
    for k in z.infolist():
        savePath=unZipPath+k.filename;
        saveDir=os.path.dirname(savePath);
        if not os.path.exists(saveDir):
            os.makedirs(saveDir);
        f=open(savePath,'wb');
        f.write(z.read(k));
        f.close();
    z.close();
    #print unZipPath
global _iterateExeZipFile;
def exeZipFile(filePath,zipFilePath=''):
    '''压缩文件
    filePath 要解压的文件路径 可以是文件或者目录
             os.sep结尾表示压缩该目录下的子文件和文件夹 不包含该文件夹,否则包含该文件夹压缩
    ZipFilePath 压缩包文件路径
                也可只传文件名
                默认压缩到filePath的父级目录下
    '''
    filePath=filePath.decode('utf-8');
    zipFilePath=zipFilePath.decode('utf-8');
    #压缩文件不存在直接返回
    if not os.path.exists(filePath):
        raise ZipException,'function exeZipFile:not exists file or dir(%s)' %filePath;
    # 是否包含父级目录压缩
    hasPDir=not filePath.endswith(os.sep);
    if not hasPDir:
        filePath=os.path.dirname(filePath);
        print filePath
    #校验备份文件路径
    if zipFilePath=='':
        zipFilePath=os.path.splitext(filePath)[0]+'.zip';
    elif zipFilePath.find(os.sep)==-1:#只传文件名的处理
        zipFilePath=os.path.dirname(filePath)+os.sep+zipFilePath;
    #校验创建备份路径目录
    if not os.path.exists(os.path.dirname(zipFilePath)):
        os.makedirs(os.path.dirname(zipFilePath));
    #初始化压缩包中的根目录
    zipRoot='';
    if hasPDir:
        zipRoot=os.path.split(filePath)[1];
    #开始压缩
    z = zipfile.ZipFile(zipFilePath, 'w')
    if os.path.isfile(filePath):
        z.write(filePath,os.path.split(filePath)[1]);
    else:
        _iterateExeZipFile(filePath,zipRoot,z);
    z.close();
def _iterateExeZipFile(dirPath,zipRoot,z):

压缩使用的例子:

if __name__=='__main__':
    #压缩包不带级父文件夹目录
    testdir='D:\\codeSource\\linuxAgent\\'
    zipFilePath='D:\\codeSource\\压缩包不带父级目录.zip'
    exeZipFile(testdir,zipFilePath);
    #压缩包带父级文件夹目录
    testdir='D:\\codeSource\\linuxAgent'#不带后缀斜线
    zipFilePath='D:\\codeSource\\压缩包带父级目录.zip'
    exeZipFile(testdir,zipFilePath);
    #不指定目标文件与路径压缩
    testdir='D:\\codeSource\\linuxAgent'
    exeZipFile(testdir);
    #指定压缩包名称不指定路径压缩
    testdir='D:\\codeSource\\linuxAgent\\'
    exeZipFile(testdir,'仅指定名称压缩包.zip');

解压的例子:

    #指定解压目录解压文件
    testdir=u'D:\\codeSource\\仅指定名称压缩包\\'
    zipFilePath=u'D:\\codeSource\\仅指定名称压缩包.zip'
    unZipFile(zipFilePath,testdir);
    #不指定目录解压
    zipFilePath=u'D:\\codeSource\\仅指定名称压缩包.zip'
    unZipFile(zipFilePath);

好了!就这么多,如果你觉得有用就顶一下吧。有问题也可以联系我

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python文件与目录操作技巧汇总》、《Python文本文件操作技巧汇总》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

pytorch实现特殊的Module--Sqeuential三种写法

我就废话不多说了,直接上代码吧! # -*- coding: utf-8 -*- #@Time :2019/7/1 13:34 #@Author :XiaoMa import...

在Python中使用正则表达式的方法

正则表达式(regular expression)是一种用形式化语法描述的文本匹配模式。在需要处理大量文本处理的应用中有广泛的使用,我没使用的编辑器,IDE中的搜索常用正则表达式作为搜索...

浅谈python中的__init__、__new__和__call__方法

前言 本文主要给大家介绍关于python中__init__、__new__和__call__方法的相关内容,分享出来供大家参考学习,下面话不多说,来一起看看详细的介绍: 任何事物都有一个...

python将ip地址转换成整数的方法

本文实例讲述了python将ip地址转换成整数的方法。分享给大家供大家参考。具体分析如下: 有时候我们用数据库存储ip地址时可以将ip地址转换成整数存储,整数占用空间小,索引也会比较方便...

Python程序设计入门(1)基本语法简介

Python是当今日趋流行的一种脚本语言,它比Java更简单,比php更强大,并且还适用于做桌面应用的开发,在ubuntu中,更加是必须的一种脚本引擎,所以有必要去学习一下,这里的文章只...