• Python使用zipfile模块压缩目录(包含空目录)、压缩文件、解压文件


    主要功能:压缩目录、压缩文件、解压文件

    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,除此之外,增加了压缩文件,解压文件。

  • 相关阅读:
    守护进程-锁-队列(生产者消费者模型)
    正则表达式不包含某个字符串写法
    正则表达式匹配不包含某些字符串的技巧
    08.参数估计_点估计
    07.编程理解中心极限定理
    05.编程理解小数和大数定律
    03.描述性统计代码
    02.描述统计 (descriptive statistics)
    oracle之三手工不完全恢复
    oracle之三手工完全恢复
  • 原文地址:https://www.cnblogs.com/gdjlc/p/16889370.html
Copyright © 2020-2023  润新知