Compress and Relocate Two Files into a Zip Archive

  • Share this:

Code introduction


This function compresses two files into a single zip file and moves this zip file to the directory of the first file.


Technology Stack : os, zipfile, shutil

Code Type : File processing

Code Difficulty : Intermediate


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

    base_name = os.path.basename(file1)
    zip_name = os.path.splitext(base_name)[0] + '.zip'
    with zipfile.ZipFile(zip_name, 'w') as zipf:
        zipf.write(file1, os.path.basename(file1))
        zipf.write(file2, os.path.basename(file2))
    shutil.move(zip_name, os.path.join(os.path.dirname(file1), zip_name))                
              
Tags: