且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在python中压缩文件夹和文件?

更新时间:2023-09-26 09:31:10

python 中的 zipfile 模块不支持添加带有文件的目录,因此需要将文件逐个添加.

The zipfile module in python has no support for adding a directory with file so you need to add the files one by one.

这是一个(未经测试的)示例,说明如何通过修改您的代码示例来实现:

This is an (untested) example of how that can be achieved by modifying your code example:

import os

zfName = 'simonsZip.kmz'
foo = zipfile.ZipFile(zfName, 'w')
foo.write("temp.kml")
# Adding files from directory 'files'
for root, dirs, files in os.walk('files'):
    for f in files:
        foo.write(os.path.join(root, f))
foo.close()
os.remove("temp.kml")