繁体   English   中英

Python - 使用循环比较两个文本文件和输出差异

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM