ZIP folder with subfolder in python

This answer is very helpful, but it took me a moment to fully understand what rootlen was for. This example uses some longer variable names to help teach what exactly is going on here. Also included is a block to validate the zip file is correct.

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

The key to making it work is the os.walk() function. Here is a script I assembled in the past that should work. Let me know if you get any exceptions.

import zipfile
import os
import sys

def zipfolder(foldername, target_dir):            
    zipobj = zipfile.ZipFile(foldername + '.zip', 'w', zipfile.ZIP_DEFLATED)
    rootlen = len(target_dir) + 1
    for base, dirs, files in os.walk(target_dir):
        for file in files:
            fn = os.path.join(base, file)
            zipobj.write(fn, fn[rootlen:])

zipfolder('thenameofthezipfile', 'thedirectorytobezipped') #insert your variables here
sys.exit()

Tags:

Python

Zip