如何在Python中比较两个文件?

时间:2014-02-13 06:47:19

标签: python

我是Python新手。我想比较两个文件(a.txt和b.txt),并将差异写入第三个文件c.txt。

a.txt的内容:

77.67.33.100 46.38.237.116 74.86.24.19 212.83.158.5 46.149.28.96 144.76.126.179 81.89.96.89 144.76.126.180 81.89.96.90 171.25.193.21 31.172.31.207 

是一行,单个字符串用空格分隔

b.txt的内容:

171.25.193.21 46.38.237.116 31.172.31.207 85.25.203.42 77.67.33.100 74.86.24.19 212.83.158.5 46.149.28.97  

我需要在c.txt中输出这样的输出:

85.25.203.42 46.149.28.97  

表示将用空格分隔的b.txt中的每个字符串与文件a.txt中的每个字符串进行比较。只有那些不存在于a.txt中的字符串才应写入c.txt

2 个答案:

答案 0 :(得分:2)

def read_file(fname):
    with open(fname) as inf:
        return [s for row in inf for s in row.split()]

def write_file(fname, items):
    with open(fname, "w") as outf:
        outf.write(" ".join(items))

def main():
    a_items = set(read_file("a.txt"))
    b_items = set(read_file("b.txt"))
    c_items = b_items - a_items
    write_file("c.txt", c_items)

if __name__=="__main__":
    main()

答案 1 :(得分:0)

a = open('a.txt').read().split()
b = open('b.txt').read().split()
c = [x for x in b if x not in a]
open('c.txt', 'wt').write(' '.join(c)+'\n')