Zipping and Relocating Two Files into a Single Zip

  • Share this:

Code introduction


This function zips two files into a single zip file and then moves the zip file to a specified location. It uses the zipfile library to create the zip file, adds the files to the zip, and then uses the shutil library to move the zip file to the target location.


Technology Stack : os, zipfile, shutil

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_file(file1, file2, output):
    import os
    import zipfile
    import shutil
    
    # 创建一个zip文件
    with zipfile.ZipFile(output, 'w') as zipf:
        # 添加文件1到zip文件
        zipf.write(file1, os.path.basename(file1))
        # 添加文件2到zip文件
        zipf.write(file2, os.path.basename(file2))
    
    # 使用shutil.move将zip文件移动到目标位置
    shutil.move(output, f"{os.path.splitext(output)[0]}_final.zip")                
              
Tags: