用Python编写一个比较两个文本文件内容是否相同的程序,若所有的段落内容完全相同,显示“compare ok”,否则显示“not equal”,并输出每个文本与另外一个文本不相同的段落内容。
时间: 2024-12-08 20:16:47 浏览: 28
在Python中,你可以使用内置的`open()`函数打开文件,并逐行比较两文件的内容。这里是一个简单的示例,使用`difflib`库来进行比较:
```python
import difflib
def compare_files(file1, file2):
# 打开并读取文件内容
with open(file1, 'r') as f1, open(file2, 'r') as f2:
content1 = f1.readlines()
content2 = f2.readlines()
# 使用Differ类进行比较
d = difflib.Differ()
diff = list(d.compare(content1, content2))
# 检查是否有差异
if not any(line.startswith('+') or line.startswith('-') for line in diff):
print("compare ok")
else:
print("not equal")
# 获取并打印不相同的段落
same_lines = [line for line in diff if not (line.startswith('+') or line.startswith('-'))]
diff_lines = [line for line in diff if line.startswith('+') or line.startswith('-')]
print("\nDifficult lines:")
for line in diff_lines:
print(line.strip())
file1_path = 'file1.txt'
file2_path = 'file2.txt' # 替换为你需要比较的实际文件名
compare_files(file1_path, file2_path)
阅读全文