Merge and Move Files into a Zip Archive

  • Share this:

Code introduction


Merge two files into a single zip file and move it 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 = f"{os.path.splitext(base_name)[0]}_merged.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))

    return zip_name                
              
Tags: