Compress and Move Two Files into a Zip File

  • Share this:

Code introduction


This function compresses two files into one zip file and moves the zip file to the output directory.


Technology Stack : os, zipfile, shutil

Code Type : File operation

Code Difficulty : Intermediate


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

    def make_zip_folder(path):
        if not os.path.exists(path):
            os.makedirs(path)

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

    shutil.move(os.path.join(output, 'output.zip'), output)

    return os.path.join(output, 'output.zip')                
              
Tags: