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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章