【问题标题】:Compare two files .txt - Python比较两个文件 .txt - Python
【发布时间】:2019-10-08 19:16:18
【问题描述】:

你能帮帮我吗?

我有两个文件 .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']

【问题讨论】:

  • 欢迎来到 SO - 我怀疑您是否对您的算法应该返回什么样的差异有明确的描述。为什么 arquivo 在两个文件中相等时是返回差异的一部分?或者程序是否应该从发现的任何差异中返回每一行的所有其余部分? IMO 你应该澄清你的要求,为你自己和你在这里问的人。

标签: python compare


【解决方案1】:

在您的文件中,第二个条目后有多余的空格和制表符

正如您在屏幕截图中看到的那样。 这就是为什么你会得到意想不到的结果

【讨论】:

    猜你喜欢
    • 2015-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-21
    相关资源
    最近更新 更多