Compress Two Files into a Zip Archive

  • Share this:

Code introduction


This function compresses two files into a single zip file.


Technology Stack : os, zipfile, tempfile

Code Type : File operation

Code Difficulty : Intermediate


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

    with tempfile.TemporaryDirectory() as temp_dir:
        with zipfile.ZipFile(os.path.join(temp_dir, 'output.zip'), 'w') as zipf:
            zipf.write(file1, os.path.basename(file1))
            zipf.write(file2, os.path.basename(file2))

        return os.path.join(temp_dir, 'output.zip')