[英]Python - Comparing two text file and output differences using loops
第一個文件:這是文本。/n abc/n 123
第二個文件:這是文本。/n xyz/n 123
我正在做一項作業,要求我打印(“否”),同時如果文件不同,還要打印第一個和第二個文件中不同的行部分。 他們要求我使用循環來比較並找到差異,而不是打印差異並在找到差異時中斷循環。 我似乎無法進入第二行文字來使我的條件成立。
secondFile = input("Enter the second file name: ")
first = open(firstFile, 'r')
second = open(secondFile, 'r')
if first.read() == second.read():
print("Yes")
else:
print("No")
while True:
firstLine = first.readline()
secondLine = second.readline()
if firstLine == secondLine:
print(first.readline())
print(second.readline())
break```
second.read()
包含文件中的所有數據,所以一旦你到達first.readline()
你只會得到空字符串。 逐行讀取文件並僅在所有行都已經比較的情況下使用for else
打印“是”。 您還應該在完成后關閉文件,您可以使用with
with open(firstFile, 'r') as file1, open(secondFile, 'r') as file2:
for line1, line2 in zip(file1, file2):
if line1 != line2:
print('No', line1, line2, sep='\n')
break
else:
print('Yes')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.