Asked  7 Months ago    Answers:  5   Viewed   54 times

How can I create a zip archive of a directory structure in Python?



As others have pointed out, you should use zipfile. The documentation tells you what functions are available, but doesn't really explain how you can use them to zip an entire directory. I think it's easiest to explain with some example code:

import os
import zipfile
def zipdir(path, ziph):
    # ziph is zipfile handle
    for root, dirs, files in os.walk(path):
        for file in files:
            ziph.write(os.path.join(root, file), 
                       os.path.relpath(os.path.join(root, file), 
                                       os.path.join(path, '..')))
zipf = zipfile.ZipFile('', 'w', zipfile.ZIP_DEFLATED)
zipdir('tmp/', zipf)
Tuesday, June 1, 2021
answered 7 Months ago

Here's a blog post which does just that:

The whole code is here:

Monday, June 28, 2021
answered 6 Months ago

The zipfile write() method supports an extra argument (arcname) which is the archive name to be stored in the zip file, so you would only need to change your code with:

from os.path import basename
zip.write(first_path, basename(first_path))
zip.write(second_path, basename(second_path))

When you have some spare time reading the documentation for zipfile will be helpful.

Monday, June 28, 2021
answered 6 Months ago

The zipfile module from the Python standard library supports only CRC32 encrypted zip files (see here: ). So, there is no way around some 3rd party dependency.

The easiest way would be to just install 7zip and call the commandline utility 7z using the subprocess module from the standard lib:

import subprocess["7z", "x", "-ppassword", ""])

Another option would be the python module "PyLzma" which can also handle AES encrypted 7zip archives: . It doesn't directly support decrypting classic zip files but you could use its routines to write your own decompressor function.

Saturday, July 31, 2021
answered 4 Months ago

I figured out a way for this: Its working for me now.

task myZip(type: Zip) {
   from 'Reports/'
   include '*'
   include '*/*' //to include contents of a folder present inside Reports directory
   archiveName ''
Monday, August 9, 2021
answered 4 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :