Merge Two Files into a Single Zip File

  • Share this:

Code introduction


This function merges two files into a single zip file. If the files exist, it creates a zip file containing both files.


Technology Stack : os, zipfile, shutil

Code Type : File operation

Code Difficulty : Intermediate


                
                    
def zipfiles(file1, file2):
    import os
    import zipfile
    import shutil

    def create_zip(source, destination):
        with zipfile.ZipFile(destination, 'w', zipfile.ZIP_DEFLATED) as zipf:
            zipf.write(source, os.path.basename(source))

    if not os.path.exists(file1) or not os.path.exists(file2):
        raise FileNotFoundError("One or both of the files do not exist.")

    zip_file_path = f"{os.path.splitext(file1)[0]}_merged.zip"
    create_zip(file1, zip_file_path)
    create_zip(file2, zip_file_path)

    return zip_file_path                
              
Tags: