使用zipfile模块创建完整目录的zip文件

1 投票
3 回答
5426 浏览
提问于 2025-04-16 09:03
zip = zipfile.ZipFile(destination+ff_name,"w")
            zip.write(source)
            zip.close()

上面是我正在使用的代码,这里的“source”是指目录的路径。但是当我运行这段代码时,它只会把源文件夹压缩,而不会把里面的文件和文件夹也压缩进去。我希望它能递归地压缩源文件夹。使用tarfile模块,我可以做到这一点,而且不需要额外提供任何信息。

3 个回答

1

我想在这个话题中添加一个“新”的 Python 2.7 特性:ZipFile 可以作为上下文管理器使用,因此你可以像这样做:

        with zipfile.ZipFile(my_file, 'w') as myzip:
            rootlen = len(xxx) #use the sub-part of path which you want to keep in your zip file 
            for base, dirs, files in os.walk(pfad):
                for ifile in files:
                    fn = os.path.join(base, ifile)
                    myzip.write(fn, fn[rootlen:])
2

我没有完全测试过这个,但它和我用的东西很相似。

zip = zipfile.ZipFile(destination+ff_name, 'w', zipfile.ZIP_DEFLATED)
rootlen = len(source) + 1
for base, dirs, files in os.walk(source):
    for file in files:
        fn = os.path.join(base, file)
        zip.write(fn, fn[rootlen:])

这个例子来自这里:

http://bitbucket.org/jgrigonis/mathfacts/src/ff57afdf07a1/setupmac.py

2

标准的 os.path.walk() 函数可能会对你非常有帮助。

另外,看看 tarfile 模块是怎么工作的也会对你有好处。实际上,研究一下标准库中一些模块的写法对我学习Python来说是非常重要的。

撰写回答