How to Convert Folders Into ZIP Format in Python?


Python is a versatile scripting language that allows you to write code for a wide range of purposes, including file compression. In this guide, we’ll show you how to compress entire folders into .zip files using Python.

Convert Folders Into ZIP Format in Python

To convert a folder into a ZIP file, you will need to import the “zipfile” module and create a ZipFile object. Zipfile is a library that allows us to work with .zip files in Python

The supported compression types are “ZIP_STORED” (no compression) and “ZIP_DEFLATED” (DEFLATE algorithm).

import os import zipfile from random import randrange def zip_dir(path, zip_handler): for root, dirs, files in os.walk(path): for file in files: zip_handler.write(os.path.join(root, file)) if __name__ == '__main__': to_zip = input(""" Enter the name of the folder you want to zip (N.B.: The folder name should not contain blank spaces) > """) to_zip = to_zip.strip() + "/" zip_file_name = f'zip{randrange(0,10000)}.zip' zip_file = zipfile.ZipFile(zip_file_name, 'w', zipfile.ZIP_DEFLATED) zip_dir(to_zip, zip_file) zip_file.close() print(f'File Saved as {zip_file_name}')
Code language: Python (python)

How to use

  • Step 1 Put the folder you want to convert in the same directory
  • Step 2 -> Run the script
    • Windows: py folder-to-zip.py
    • Linux: python3 folder-to-zip.py

Download Script Here

ZIP folder with subfolder in python

import os import zipfile src_path = os.path.join('/', 'some', 'src', 'path') archive_name = 'myZipFile.zip' archive_path = os.path.join('/', 'some', 'path', archive_name) with zipfile.ZipFile(archive_path, 'w', zipfile.ZIP_DEFLATED) as archive_file: for dirpath, dirnames, filenames in os.walk(src_path): for filename in filenames: file_path = os.path.join(dirpath, filename) archive_file_path = os.path.relpath(file_path, src_path) archive_file.write(file_path, archive_file_path) with zipfile.ZipFile(archive_path, 'r') as archive_file: bad_file = zipfile.ZipFile.testzip(archive_file) if bad_file: raise zipfile.BadZipFile( 'CRC check failed for {} with file {}'.format(archive_path, bad_file))
Code language: Python (python)

And there you have it—a quick and easy guide to compressing folders into ZIP format using Python! By following the steps outlined above, you’ll be able to convert any folder on your computer into a ZIP file within minutes. As always, if you have any questions or run into any issues along the way, feel free to reach out to us in the comments below and we’ll be happy to help!

Andy Avery

I really enjoy helping people with their tech problems to make life easier, ​and that’s what I’ve been doing professionally for the past decade.

Recent Posts