Merge Two Files into a Zip File

  • Share this:

Code introduction


This function merges the contents of two files into a single zip file. It first creates a zip file and then adds the contents of the two files to this zip file.


Technology Stack : zipfile, os

Code Type : File processing

Code Difficulty : Intermediate


                
                    
def zip_file(file1, file2):
    """
    将两个文件的内容合并为zip文件。
    """
    import zipfile
    import os

    # 创建一个zip文件
    with zipfile.ZipFile('output.zip', 'w') as zipf:
        # 添加file1到zip文件
        zipf.write(file1, os.path.basename(file1))
        # 添加file2到zip文件
        zipf.write(file2, os.path.basename(file2))

    return "output.zip"                
              
Tags: