将一个主文本文件与多个文本文件进行比较,并在python中打印差异

时间:2018-02-22 21:43:31

标签: python python-2.7

我在python中有一个工作代码,比较两个文本文件并打印差异,但是现在我需要将一个主文件(file1)与多个文件(文件2,文件3 ...)在同一目录中进行比较并打印差异

注意:主文件(file1)的内容永远不会改变

For Example:

    File1 has
    boy1
    boy2
    boy3

    File2
    boy1
    boy4
    boy5

    File 3
    boy2
    boy6
    boy7

Desired output 

     #in file1 but not file2
      boy2
      boy3
     #in file1 but not file3
      boy1
      boy3
    ...





Code for comparing two files and printing delta


    with open('file1.txt') as f:
            t1 = f.read().splitlines()
            t1s = set(t1)

        with open('file2.txt') as f:
            t2 = f.read().splitlines()
            t2s = set(t2)

        #in file1 but not file2
        print "Only in file1"
        for diff in t1s-t2s:
            print t1.index(diff), diff

        #in file2 but not file1
        print "Only in file2"
        for diff in t2s-t1s:
            print t2.index(diff), diff

0 个答案:

没有答案