Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19k points)

In Python, hHow to create a zip archive of a directory structure?

2 Answers

0 votes
by (106k points)

To create a zip archive of a directory you can use the shutil.make_archive() the function which supports the zip format. Below is the code for the same. 

import shutil

shutil.make_archive(output_filename, 'zip', dir_name)

Another way is by using the zipfile. Below I have given the code that shows you how it can be used:

#!/usr/bin/env python

import os

import zipfile

def zipdir(path, ziph):

    for root, dirs, files in os.walk(path):

          for file in files:

                ziph.write(os.path.join(root, file)) 

if __name__ == '__main__':  #This is driver code

       zipf = zipfile.ZipFile('Python.zip', 'w', zipfile.ZIP_DEFLATED)

       zipdir('tmp/', zipf)

       zipf.close()

0 votes
by (108k points)
edited by

I would suggest you use the zipfile module from python. Kindly check the below code for reference:

#!/usr/bin/env python

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

if __name__ == '__main__':

    zipf = zipfile.ZipFile('Python.zip', 'w', zipfile.ZIP_DEFLATED)

    zipdir('tmp/', zipf)

    zipf.close()

Are you interested to learn Python in detail? Do check out the below video for more insights:

Related questions

0 votes
1 answer
0 votes
0 answers
asked Jun 24, 2021 in Linux by akhil.singh0123123 (320 points)
0 votes
2 answers
asked Jul 6, 2019 in Python by Sammy (47.6k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

29.3k questions

30.6k answers

501 comments

104k users

Browse Categories

...