Compress Two Files into a Single Zip File

  • Share this:

Code introduction


This function compresses two files into a single zip file and returns the path to the generated zip file.


Technology Stack : os, zipfile

Code Type : Function

Code Difficulty : Intermediate


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

    # Check if the output file exists and remove it to create a new zip file
    if os.path.exists(output):
        os.remove(output)

    # Create a zip file
    with zipfile.ZipFile(output, 'w') as zipf:
        # Add file1 to the zip file
        zipf.write(file1, os.path.basename(file1))
        # Add file2 to the zip file
        zipf.write(file2, os.path.basename(file2))

    return output                
              
Tags: