pythonzippython-zipfile

Python: Zipping the subfolders including inside the data


I am trying to make the script for zipping the subfolders including inside files, and sub subfolders as well as it's own in python. below program is by entering the folder name but still, it won't work. Please, somebody, help with the script. Thank you so much in advance.

import zipfile
import os
import sys

def zipfolder(foldername, target_dir):            
    zipobj = zipfile.ZipFile(foldername + '.zip', 'w', zipfile.ZIP_DEFLATED)
    rootlen = len(target_dir) + 1
    for base, dirs, files in os.walk(target_dir):
        for file in files:
            fn = os.path.join(base, file)
            zipobj.write(fn, fn[rootlen:])

zipfolder('20220711_RX_2_nomaly', '20220711_RX_3_nomaly') #insert your variables here
sys.exit()

structure of the subfolders and inside the files.

 main folder(folder)
  20220711_RX_2_nomaly(folder)
    grey(folder)
      xxxxx.jpg (files)
    json (folder)
       xxxx.json(files)
  20220711_RX_3_nomaly(folder)
    grey(folder)
      xxxxx.jpg (files)
    json (folder)
       xxxx.json(files)      
  20220711_RX_4_nomaly(folder)
    grey(folder)
      xxxxx.jpg (files)
    json (folder)
       xxxx.json(files)

expected

20220711_RX_2_nomaly.zip
20220711_RX_3_nomaly.zip
20220711_RX_4_nomaly.zip

Solution

  • To create a zip archive you can use the ZipFile class from the zipfile module.

    import os
    from zipfile import ZipFile, ZIP_DEFLATED
    
    def zipfolders(*args):
        """
        Creates identically named zip archives of folders provided.
        example: zipfolders(path1, path2, path3)
        output -> path1.zip | path2.zip | path3.zip
    
        Parameters
        ----------
        args : tuple
            A sequence of string paths to folders that need to be archived.
        """
        for foldername in args:
            zipfolder(foldername, foldername)
    
    def zipfolder(foldername, target_dir):
        """
        This function receives two paths as arguments and creates a zip archive.
        example: zipfolder("future_foldername", "current_source")
        output -> future_foldername.zip
        
        Parameters
        ----------
        foldername : str
            This is the name of the zip archive that will be created.
        target_dir : str
            This is the path to the source files/folders to archive
        """
        archive = ZipFile(foldername + '.zip', 'w', ZIP_DEFLATED)
        for root, _, files in os.walk(target_dir):
            for filename in files:
                fullpath = os.path.join(root, filename)
                archive.write(fullpath)
        print(f"Successfully created archive {foldername}.zip")