Combine and Compress Two Text Files into a Zip

  • Share this:

Code introduction


Combine the contents of two text files into a single zip file.


Technology Stack : Built-in library (zipfile)

Code Type : File processing

Code Difficulty : Intermediate


                
                    
def zip_file(file1, file2, output):
    """
    将两个文件的内容合并,并压缩成zip文件。
    """
    with open(file1, 'r') as f1, open(file2, 'r') as f2, open(output, 'wb') as out:
        with zipfile.ZipFile(out, 'w') as zipf:
            zipf.writestr('file1.txt', f1.read())
            zipf.writestr('file2.txt', f2.read())