Compress and Extract Two Files into a Zip File

  • Share this:

Code introduction


This function compresses two files into one zip file, then extracts this zip file into an output file, and finally deletes the temporary files.


Technology Stack : File operations, temporary files, zip file processing

Code Type : Function

Code Difficulty : Advanced


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

    with tempfile.NamedTemporaryFile(delete=False) as tmp:
        with zipfile.ZipFile(tmp.name, 'w') as zipf:
            zipf.write(file1)
            zipf.write(file2)
    
    with zipfile.ZipFile(tmp.name, 'r') as zipf:
        with open('output.zip', 'wb') as output:
            output.write(zipf.read('test.zip'))
    
    shutil.rmtree(os.path.dirname(tmp.name))
    return 'output.zip'