File size: 835 Bytes
81302b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from difflib import ndiff

def merge_file1_file2(file1_path, file2_path, output_path):
    with open(file1_path, 'r') as f1, open(file2_path, 'r') as f2:
        file1_lines = f1.readlines()
        file2_lines = f2.readlines()

    diff = list(ndiff(file1_lines, file2_lines))
    merged = []

    for line in diff:
        if line.startswith("  "):  # common line
            merged.append(line[2:])
        elif line.startswith("- "):  # only in file1
            merged.append(line[2:])  # keep it
        elif line.startswith("+ "):  # only in file2
            merged.append(line[2:])  # add it
        # we ignore changed lines, since - and + will appear, but we keep file1 version

    with open(output_path, 'w') as out:
        out.writelines(merged)

# Example usage
merge_file1_file2("file1.txt", "file2.txt", "merged.txt")