Combine and Move Files into Zip

  • Share this:

Code introduction


Combine two files into a single zip file and move it to the directory of the first file.


Technology Stack : os, zipfile, shutil

Code Type : Function

Code Difficulty : Intermediate


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

    base_name = os.path.basename(file1)
    zip_name = f"{os.path.splitext(base_name)[0]}_combined.zip"

    with zipfile.ZipFile(zip_name, 'w') as zipf:
        zipf.write(file1, arcname=os.path.basename(file1))
        zipf.write(file2, arcname=os.path.basename(file2))

    shutil.move(zip_name, os.path.join(os.path.dirname(file1), zip_name))

    return zip_name                
              
Tags: