All Courses

How to Write Python ZIP File?

By Subham, 2 years ago
  • Bookmark

I want to create zip file and add some text files into it

1 Answer

We use the write() method to write to a ZIP.

# importing required modules
from zipfile import ZipFile
import os
def get_all_file_paths(directory):
    # initializing empty file paths list
    file_paths = []
    # crawling through directory and subdirectories
    for root, directories, files in os.walk(directory):
      for filename in files:
          # join the two strings in order to form the full filepath.
          filepath = os.path.join(root, filename)
    # returning all file paths
    return file_paths     
def main():
    # path to folder which needs to be zipped
    directory = './python_files'
    # calling function to get all file paths in the directory
    file_paths = get_all_file_paths(directory)
    # printing the list of all files to be zipped
    print('Following files will be zipped:')
    for file_name in file_paths:
    # writing files to a zipfile
    with ZipFile('','w') as zip:
        # writing each file one by one
        for file in file_paths:
    print('All files zipped successfully!')     
if __name__ == "__main__":


Following files will be zipped:
All files zipped successfully!

In [ ]:

Now let’s see how this works:

We create a function with uses the method os.walk(). In every iteration, it appends the files in that directory to the list paths.

Then, we get a list of the file paths bypassing the Demo directory’s path to the function get_paths().

Then, we create a ZipFile object in WRITE mode. Finally, we use the write() method to write all these files to the ZIP.

Your Answer


Live Masterclass on : "How Machine Get Trained in Machine Learning?"

Jun 1st (5:32 PM) 515 Registered
More webinars

Related Discussions

Running random forest algorithm with one variable

View More