且构网

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

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

更新时间:2023-09-26 09:26:22

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")