-1

test1.txt内容如下:

Hi, how are you ?
It's already late.
My name is Sayan.

test2.txt内容如下:

My name is Sayan.
It's already late.
Hi, how are you ?

在我的场景中,这两个文件在内容方面都是相同的。

我想创建一个脚本(基本上不使用sort, comm, cmp, diff)来比较这两个文件,test1.txt并且test2.txt,内容明智并产生结果:

File Comparison status - Success 

或者如果内容不同,那么

File Comparison status - Failed  [ check in result.txt ] 

哪里result.txt会列出额外的、缺失的或修改过的内容。

脚本可以在 Bash 或/和 Python 中。我怎样才能做到这一点?

4

1 回答 1

0

如果文件不是太大,您可以使用sorted()对行进行排序并比较结果列表。要生成文件内容的差异,您可以使用该difflib模块:

import difflib    

with open('file1') as f1, open('file2') as f2:
    f1_lines = sorted(f1)
    f2_lines = sorted(f2)

    if f1_lines == f2_lines:
        print("Equal so far")

    f2_lines.append("Extra line\n")

    print("".join(difflib.unified_diff(f1_lines, f2_lines)))

输出:

Equal so far
--- 
+++ 
@@ -1,3 +1,4 @@
 Hi, how are you ?
 It's already late.
 My name is Sayan.
+Extra line
于 2018-04-28T19:27:04.113 回答