如何在python中压缩文件夹和文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22465629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to zip a folder and file in python?
提问by BubbleMonster
I've got a folder called: 'files' which contains lots of jpg photographs. I've also got a file called 'temp.kml'. I want to create a KMZ file (basically a zip file) which contains the temp.kml file AND the files directory which has the photographs sitting inside it.
我有一个名为:'files' 的文件夹,其中包含许多 jpg 照片。我还有一个名为“temp.kml”的文件。我想创建一个 KMZ 文件(基本上是一个 zip 文件),其中包含 temp.kml 文件和包含照片的文件目录。
Here is my code:
这是我的代码:
zfName = 'simonsZip.kmz'
foo = zipfile.ZipFile(zfName, 'w')
foo.write("temp.kml")
foo.close()
os.remove("temp.kml")
This creates the kmz file and puts the temp.kml inside. But I also want to put the folder called 'files' in as well. How do I do this?
这将创建 kmz 文件并将 temp.kml 放入其中。但我也想把名为“files”的文件夹也放进去。我该怎么做呢?
I read here on StackOverflow that some people have used shutil to make zip files. Can anyone offer a solution?
我在 StackOverflow 上读到,有些人使用 Shutil 制作 zip 文件。任何人都可以提供解决方案吗?
采纳答案by HAL
The zipfile module in python has no support for adding a directory with file so you need to add the files one by one.
python中的zipfile模块不支持添加文件目录,需要一个一个的添加。
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")

