How to zip a folder and file in python?

后端 未结 3 1787
情深已故
情深已故 2021-01-12 05:04

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

3条回答
  •  时光说笑
    2021-01-12 05:16

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

提交回复
热议问题