要一直走下去

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

zipfile压缩文件。包括空目录

 

# !/usr/bin/python
import os
import zipfile


def zipdir(dirPath=None, zipFilePath=None, includeDirInZip=True):
    if not zipFilePath:
        zipFilePath = dirPath + ".zip"
    if not os.path.isdir(dirPath):
        raise OSError("必须指定一个目录, '%s'不是目录。" % dirPath)
    parentDir, dirToZip = os.path.split(dirPath)
    # parentDir=C:\Users\Administrator\Desktop\菊花号
    # dirToZip=abc


    # Little nested function to prepare the proper archive path
    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)
    for (archiveDirPath, dirNames, fileNames) in os.walk(dirPath):
        print(archiveDirPath)
        print(dirNames)
        print(fileNames)
        for fileName in fileNames:
            filePath = os.path.join(archiveDirPath, fileName)

            outFile.write(filePath, trimPath(filePath))
        # Make sure we get empty directories as well
        if not fileNames and not dirNames:
            zipInfo = zipfile.ZipInfo(trimPath(archiveDirPath) + "/")
            # print(trimPath(archiveDirPath) + "/")
            # some web sites suggest doing
            # zipInfo.external_attr = 16
            # or
            # zipInfo.external_attr = 48
            # Here to allow for inserting an empty directory.  Still TBD/TODO.
            outFile.writestr(zipInfo, "")
    outFile.close()

if __name__ == '__main__':
    zipdir("C:\\Users\\Administrator\\Desktop\\菊花号\\abc",
           "C:\\Users\\Administrator\\Desktop\\菊花号\\abc.zip")

 

posted on 2022-05-19 23:11  要一直走下去  阅读(455)  评论(0编辑  收藏  举报