Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ZIP folder with subfolder in python

Tags:

python

zip

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.

like image 417
Z77 Avatar asked May 07 '12 09:05

Z77


People also ask

Can you zip folders with subfolders?

Creating a zip folder allows files to be organized and compressed to a smaller file size for distribution or saving space. Zip folder can have subfolders within this main folder.

How do I create a directory and subfolder in Python?

Creating a Directory with Subdirectories Actually, makedirs() is implemented in such a way that it calls mkdir() to create one directory after the next. As a parameter makedirs() accepts the entire path to be created. This method is similar to the UNIX/Linux command mkdir -p .

What is ZipFile in Python?

Python's zipfile is a standard library module intended to manipulate ZIP files. This file format is a widely adopted industry standard when it comes to archiving and compressing digital data. You can use it to package together several related files.


1 Answers

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()
like image 107
James Milner Avatar answered Sep 23 '22 00:09

James Milner