How to zip a folder and file in python?

社会主义新天地 提交于 2019-12-19 05:54:08

问题


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.

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?

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


回答1:


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



回答2:


You can use shutil

import shutil

shutil.make_archive("simonsZip", "zip", "files")


来源:https://stackoverflow.com/questions/22465629/how-to-zip-a-folder-and-file-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!