要比較兩個文件的不同,可以使用以下步驟來實現:
下面是一個示例代碼:
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
文件中。您可以根據需要修改文件名和路徑。