Merge Two Files into a Single Zip File

  • Share this:

Code introduction


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


Technology Stack : zipfile, os

Code Type : Function

Code Difficulty : Intermediate


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

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

    return 'output.zip'                
              
Tags: