要比较两个文件的不同,可以使用以下步骤来实现:
下面是一个示例代码:
import difflib
def compare_files(file1, file2, output_file):
with open(file1, 'r') as f1, open(file2, 'r') as f2:
lines1 = f1.readlines()
lines2 = f2.readlines()
differ = difflib.SequenceMatcher(None, lines1, lines2)
opcodes = differ.get_opcodes()
with open(output_file, 'w') as output:
for opcode, start1, end1, start2, end2 in opcodes:
if opcode == 'replace':
output.write(f'Different line in file1: {lines1[start1:end1]}')
output.write(f'Different line in file2: {lines2[start2:end2]}')
elif opcode == 'delete':
output.write(f'Extra line in file1: {lines1[start1:end1]}')
elif opcode == 'insert':
output.write(f'Extra line in file2: {lines2[start2:end2]}')
file1 = 'file1.txt'
file2 = 'file2.txt'
output_file = 'diff.txt'
compare_files(file1, file2, output_file)
上述代码将比较两个文件file1.txt
和file2.txt
的内容,并将不同的行保存在diff.txt
文件中。您可以根据需要修改文件名和路径。