How to Write Python ZIP File?

By Subham, 6 months ago
  • Bookmark
0

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

Zip
Python
1 Answer
0

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


# importing required modules
from zipfile import ZipFile
import os
os.chdir('C:\\Users\\Om\\Desktop')
  
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)
          file_paths.append(filepath)
  
    # 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:
        print(file_name)
  
    # writing files to a zipfile
    with ZipFile('python_files.zip','w') as zip:
        # writing each file one by one
        for file in file_paths:
            zip.write(file)
  
    print('All files zipped successfully!')     
  
  
if __name__ == "__main__":
    main()

Output


Following files will be zipped:
./python_files\setup.txt
./python_files\add.py
./python_files\logo.JPG
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

Webinars

More webinars

Related Discussions

Running random forest algorithm with one variable

View More
We're Online!

Chat now for any query