如何使用 Python 创建文件路径的 zip 文件,包括空目录? [英] How do I create a zip file of a file path using Python, including empty directories?
问题描述
我一直在尝试使用 zipfile
和 shutil.make_archive
模块递归地创建目录的 zip 文件.两个模块都工作得很好——除了空目录不会被添加到档案中.包含其他空目录的空目录也会被静默跳过.
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--except empty directories do not get added to the archive. Empty directories containing other empty directories are also silently skipped.
我可以使用 7Zip 创建相同路径的存档,并保留空目录.因此我知道这在文件格式本身中是可能的.我只是不知道如何在 Python 中做到这一点.有任何想法吗?谢谢!
I can use 7Zip to create an archive of the same path and empty directories are preserved. Therefore I know this is possible within the file format itself. I just don't know how to do it within Python. Any ideas? Thanks!
推荐答案
有一个使用 zipfile 的例子:
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')
这篇关于如何使用 Python 创建文件路径的 zip 文件,包括空目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!