How do I create a zip file of a file path using Python, including empty directories?

后端 未结 4 1881
灰色年华
灰色年华 2020-12-30 14:55

I\'ve been trying to use the zipfile and shutil.make_archive modules to recursively create a zip file of a directory. Both modules work great--exc

4条回答
  •  情歌与酒
    2020-12-30 15:12

    There is a example using 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')
    

提交回复
热议问题