Merging Two Files Line by Line

  • Share this:

Code introduction


This function merges the content of two files line by line and writes the merged content to a specified output file.


Technology Stack : File operations (open, read, write), string concatenation (+), zip object

Code Type : File processing

Code Difficulty : Intermediate


                
                    
def zip_file(file1, file2, output):
    """
    将两个文件的内容合并,并将结果保存到输出文件中。
    """
    with open(file1, 'r') as f1, open(file2, 'r') as f2, open(output, 'w') as out:
        for line1, line2 in zip(f1, f2):
            out.write(line1 + line2)