Combine and Copy Files into Zip Archive

  • Share this:

Code introduction


This function compresses two files into a single zip file and then copies the zip file to a specified output directory.


Technology Stack : os, zipfile, shutil

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zipfiles(file1, file2):
    import os
    import zipfile
    import shutil
    
    # 创建zip文件
    zip_filename = "combined.zip"
    with zipfile.ZipFile(zip_filename, 'w') as zipf:
        zipf.write(file1)
        zipf.write(file2)
    
    # 复制文件到目标目录
    shutil.copy(zip_filename, 'output_directory')
    os.remove(zip_filename)                
              
Tags: