比较两个文件.txt-Python

时间:2019-10-08 19:16:18

标签: python compare

你能帮我吗?

我有两个.txt文件,它们之间存在差异,我需要将它们进行比较并说出差异是什么,在哪里。

我编写了一个简单的代码,但仍然没有回答我。

文件1:

123
1234
12345           
123456
1234567
12345678
123456789
1234567890
saída do arquivo

文件2:

123
1234
12345
123456          
1234567
12345678
123456789
1234567890
fim de arquivo
  

程序应返回:

File1: saída do arquivo - line 9

File2: fim de arquivo - line 9

我的代码:

test_lines = open('teste1.txt').readlines()
correct_lines = open('teste2.txt').readlines()

for test, correct in zip(test_lines, correct_lines):
    if test != correct:
        print (("Oh no! Expected %r; got %r." )% (correct, test));
        break
    else:
        len_diff = len(test_lines) - len(correct_lines)
        if len_diff > 0:
            print ("Test file had too much data.")
        elif len_diff < 0:
            print ("Test file had too little data.")
        else:
            print ("Everything was correct!")

    lista_final = list(set(test_lines) - set(correct_lines))

print(lista_final)
  

它实际返回的内容:

['12345\t\t\t\n', '123456\n', 'saída do arquivo']

1 个答案:

答案 0 :(得分:0)

在文件中,第二个输入项后有多余的空格和制表符 screenshot

如屏幕截图所示。 这就是为什么您得到意想不到的结果