【发布时间】:2021-10-03 22:51:12
【问题描述】:
我需要获取两个文本文件并比较它们以查看它们是否相同或不同。如果它们相同,则输出“Yes”,如果它们不同,则输出“No”。它还将打印出两个文本文件之间的差异。例如,如果一个文本文件有这样的:
- 世界你好!
- abc
另一个文本文件有这个:
- 世界你好!
- xyz
那么输出将是:
- 没有
- abc
- xyz
firstFile = input("Enter the first file name: ")
secondFile = input("Enter the second file name: ")
f1 = open(firstFile,'r')
f2 = open(secondFile,'r')
i = 0
for line1 in f1:
i += 1
for line2 in f2:
# matching line1 from both files
if line1 == line2:
# print IDENTICAL if similar
print("Yes")
else:
print("Line ", i, ":")
# else print that line from both files
print("\tFile 1:", line1, end='')
print("\tFile 2:", line2, end='')
【问题讨论】:
-
如果行相同但上面的代码输出“是”并且注释说打印“相同”,则说明说输出应该是“否”。请澄清正确的输出。
标签: python compare text-files