我如何使用Python创建文件路径的zip文件,包括空目录?

问题描述 投票:5回答:4

我一直在尝试使用zipfileshutil.make_archive模块来递归创建目录的zip文件。这两个模块都很好用-除了不将空目录添加到存档中。也默默地跳过包含其他空目录的空目录。

我可以使用7Zip创建相同路径的档案,并保留空目录。因此,我知道在文件格式本身中这是可能的。我只是不知道如何在Python中执行此操作。有任何想法吗?谢谢!

python zip zipfile shutil
4个回答
13
投票

有一个使用zipfile的示例:

import os, zipfile  
from os.path import join  
def zipfolder(foldername, filename, includeEmptyDIr=True):   
    empty_dirs = []  
    zip = zipfile.ZipFile(filename, 'w', zipfile.ZIP_DEFLATED)  
    for root, dirs, files in os.walk(foldername):  
        empty_dirs.extend([dir for dir in dirs if os.listdir(join(root, dir)) == []])  
        for name in files:  
            zip.write(join(root ,name))  
        if includeEmptyDIr:  
            for dir in empty_dirs:  
                zif = zipfile.ZipInfo(join(root, dir) + "/")  
                zip.writestr(zif, "")  
        empty_dirs = []  
    zip.close() 

if __name__ == "__main__":
    zipfolder('test1/noname/', 'zip.zip')

0
投票

您需要register a new archive format来执行此操作,因为默认的ZIP存档程序不支持该功能。看一下the meat of the existing ZIP archiver。制作自己的存档器,该存档器使用当前未使用的dirpath变量创建目录。我寻找了如何创建一个空目录并找到this

zip.writestr(zipfile.ZipInfo('empty/'), '')

这样,您应该能够编写必要的代码,以使其存档空目录。


0
投票

这是从Adding folders to a zip file using python中取消的,但这是我尝试过的唯一起作用的功能。列出的答案在Python 2.7.3下不起作用(不会复制空目录并且效率低下)。以下内容已经过尝试和测试:

#!/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("dirPath argument must point to a directory. "
        "'%s' does not." % dirPath)
    parentDir, dirToZip = os.path.split(dirPath)
    #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 os.path.normcase(archivePath)

    outFile = zipfile.ZipFile(zipFilePath, "w",
        compression=zipfile.ZIP_DEFLATED)
    for (archiveDirPath, dirNames, fileNames) in os.walk(dirPath):
        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) + "/")
            #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()

0
投票

((我仍然没有声誉,无法直接发表评论)

建议编辑詹姆斯的答案,

更改:'def zipdir(dirPath = None,zipFilePath = None,....'到:'def zipdir(dirPath,zipFilePath = None,...'要么删除'if not os.path.isdir(dirPath):'条件及其主体

否则,由于不一致,您将遇到问题。

© www.soinside.com 2019 - 2024. All rights reserved.