Skip to content

Python create zip file

  • by

Python creates zip files using functions in the zipfile module.

from zipfile import ZipFile

Note: Install them with pip or using PyCharm IDE if any of the packages are missing on your system.

Check the official documentation.

Python creates a zip file

Simple example code creating a zip file with compression in python using the zipfile module.

from zipfile import ZipFile

if __name__ == '__main__':
    single_file = 'file01.txt'

    with ZipFile('modules/file01.zip', mode='w') as zf:
        zf.write(single_file)

Output:

Python creates a zip file

Is there any method to compress ZIP files in python?

Answer: try different compresslevel i.e.

with zipfile.ZipFile(f'{directory_name}.zip', 'w', zipfile.ZIP_DEFLATED, compresslevel=0) as zipf:

to

with zipfile.ZipFile(f'{directory_name}.zip', 'w', zipfile.ZIP_DEFLATED, compresslevel=9) as zipf:

Do comment if you have any doubts or suggestions on this Python zipfile 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