Merging Two Files into a Zip File

  • Share this:

Code introduction


This function takes two file paths as arguments and merges the contents of these two files into a zip file, saving the result to a file named 'output.zip'.


Technology Stack : zipfile

Code Type : File operation

Code Difficulty : Intermediate


                
                    
def zip_file(file1, file2):
    """
    将两个文件的内容合并为一个zip文件,并将合并后的文件保存为第三个参数指定的文件名。
    """
    with open(file1, 'rb') as f1, open(file2, 'rb') as f2:
        with zipfile.ZipFile('output.zip', 'w') as zipf:
            zipf.writestr('file1.txt', f1.read())
            zipf.writestr('file2.txt', f2.read())                
              
Tags: