如何在python中压缩文件夹和文件? [英] How to zip a folder and file in python?

查看:1132
本文介绍了如何在python中压缩文件夹和文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为"files"的文件夹,其中包含许多jpg照片.我还有一个名为"temp.kml"的文件.我想创建一个KMZ文件(基本上是一个zip文件),其中包含temp.kml文件和包含照片的文件目录.

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.

这是我的代码:

zfName = 'simonsZip.kmz'
foo = zipfile.ZipFile(zfName, 'w')
foo.write("temp.kml")
foo.close()
os.remove("temp.kml")

这将创建kmz文件,并将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?

我在这里在StackOverflow上读到一些人已经使用shutil来制作zip文件.谁能提供解决方案?

I read here on StackOverflow that some people have used shutil to make zip files. Can anyone offer a solution?

推荐答案

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

这篇关于如何在python中压缩文件夹和文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆