Asked  7 Months ago    Answers:  5   Viewed   54 times

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

 Answers

94

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('Python.zip', 'w', zipfile.ZIP_DEFLATED)
zipdir('tmp/', zipf)
zipf.close()
Tuesday, June 1, 2021
 
The_Perfect_Username
answered 7 Months ago
31

Here's a blog post which does just that: http://peekaboo-vision.blogspot.com/2012/11/a-wordcloud-in-python.html

The whole code is here: https://github.com/amueller/word_cloud

Monday, June 28, 2021
 
Marcelo
answered 6 Months ago
34

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))
zip.close()

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

Monday, June 28, 2021
 
Jimenemex
answered 6 Months ago
69

The zipfile module from the Python standard library supports only CRC32 encrypted zip files (see here: http://hg.python.org/cpython/file/71adf21421d9/Lib/zipfile.py#l420 ). 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
subprocess.call(["7z", "x", "-ppassword", "test.zip"])

Another option would be the python module "PyLzma" which can also handle AES encrypted 7zip archives: https://github.com/fancycode/pylzma . 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
 
Mirko
answered 4 Months ago
44

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 'Reports.zip'
   destinationDir(file('/dir1/dir2/dir3/'))
}
Monday, August 9, 2021
 
njeoo
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 :
 
Share