Skip to content

Python zip folder

  • by

The easiest way to zip a folder is to use shutil.make_archive in Python. It supports both zip and tar formats.

import shutil
shutil.make_archive(output_filename, 'zip', dir_name)

Python zip folder

Simple example code.

import shutil

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

Output:

Python zip folder

How to zip a folder and file in python?

Answer: The zipfile module in python has no support for adding a directory with files 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")

Source: https://stackoverflow.com/questions/

Do comment if you have any doubts or suggestions on this Python zip topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading