10
votes

I need to zip a folder that containts an .xml file and a .fgdb file by using python. Could anyone help me? I tried a few scripts I found on internet but there is always some technical issue (such as creating an empty zip file, or create zip file I cannot open 'no permission' etc..)

Thanks in advance.

3

3 Answers

20
votes

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()
1
votes

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

If someone wants some generic function to utilize in your project

def zip_compression_tree(root_path, zip_name):
with zipfile.ZipFile(zip_name, 'w') as z:
    for root, dirs, files in os.walk(root):
        for file in files:
            z.write(os.path.join(root, file))
        for directory in dirs:
            z.write(os.path.join(root, directory))