用Python写的一个小工具。用来快速比较两个文件有什么不同点,废话少说上代码。
import difflib
def compare_files(file1, file2):
# Open the two files
with open(file1, 'r') as f1, open(file2, 'r') as f2:
# Read the content of the two files
file1_content = f1.readlines()
file2_content = f2.readlines()
# Create a difflib object to compare the two files
diff = difflib.unified_diff(file1_content, file2_content)
# Print the differences in different colors
for line in diff:
if line.startswith('+'):
print("\033[92m" + line + "\033[0m")
# green for additions
elif line.startswith('-'):
print("\033[91m" + line + "\033[0m")
# red for deletions
else: print(line)
# Example usage:
compare_files("file1.txt", "file2.txt")
使用只需将最后运行的file1.txt和file2.txt替换为你真实电脑上的路径。
此代码打开这两个文件,将它们的内容读入两个单独的列表,并使用 difflib 库中的 unified_diff 函数来比较这两个文件。然后将产生的差异以不同的颜色打印出来,绿色为添加,红色为删除,从而更容易看出两个文件之间的差异。