Merging Files into a Single Zip Archive

  • Share this:

Code introduction


This function merges two files into a single zip file. The first argument file1 is used as the root directory of the zip file, the second argument file2 is the file to be added, and the output argument output specifies the path of the generated zip file.


Technology Stack : shutil, zipfile, os

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_file(file1, file2, output):
    import shutil
    import zipfile

    def zip_dir(dir_path, zip_path):
        with zipfile.ZipFile(zip_path, 'w') as zipf:
            for foldername, subfolders, filenames in os.walk(dir_path):
                for filename in filenames:
                    file_path = os.path.join(foldername, filename)
                    zipf.write(file_path, os.path.relpath(file_path, dir_path))

    shutil.copy(file1, output)
    zip_dir(file2, output)
    return output                
              
Tags: