Zip Two Files into a Single Zip File

  • Share this:

Code introduction


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


Technology Stack : os, zipfile

Code Type : Function

Code Difficulty : Advanced


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

    # Check if the files exist
    if not os.path.exists(file1) or not os.path.exists(file2):
        return "Error: One of the files does not exist."

    # Create a new zipfile
    with zipfile.ZipFile(output, 'w') as zipf:
        zipf.write(file1, os.path.basename(file1))
        zipf.write(file2, os.path.basename(file2))

    return f"Files {file1} and {file2} have been successfully zipped into {output}."                
              
Tags: