如何读取两个文件并使用与两个文件匹配的内容编写文件并写入不匹配的文件?

时间:2014-05-29 02:27:11

标签: python file input

这是我的剧本

 fo1=open("foo1.txt","wt")
 fo1.write('bangalore\n')
 fo1.write("delhi\n")
 fo1.write("mumbai\n")
 fo1.close()
 fo2=open("foo2.txt","wt")
 fo2.write("bangalore\n")
 fo2.write("chennai\n")
 fo2.write("mumbai\n")
 fo2.close()
 file1=open("foo1.txt","r+")
 file2=open("foo2.txt","r+")
 FO=open("output.txt","wt")
 FO1=open("output1.txt","wt")
 x=file1.readlines()
 y=file2.readlines()
 for line1 in x:
     for line2 in y:
         if line1 == line2:
             FO.write(line1)
//write FO1 with the content which doenot match
 FO.close()
 FO1.close()
 file1.close()
 file2.close()

并且输出应该是这样的 FO应该

bangalore
mumbai

FO1应该有

chennai
delhi

如何读取两个文件并使用与两个文件匹配的内容编写文件并写入不匹配的文件?

4 个答案:

答案 0 :(得分:1)

你很亲密。您唯一缺少的是您需要从第二个列表中删除公共元素,然后在第二个列表中写出剩余的项目。

x=file1.readlines()
y=file2.readlines()
for line1 in x:
    if line1 in y:
        FO.write(line1)
        y.remove(line1)
    else:
        FO1.write(line1)
for line2 in y:
   FO1.write(line2)

答案 1 :(得分:1)

将x和y转换为set然后使用交集和差异方法,请参阅此link

示例:

FO.write(set(x) & set(y))
FO1.write('\n'.join((set(x) - set(y) | set(y) - set(x))))

答案 2 :(得分:1)

您可以尝试这样:

FO1=open("output1.txt","wt")
FO2=open("output2.txt","wt")
one=file1.readlines()
two=file2.readlines()
for line1 in one:
    if line1 in two:
        FO1.write(line1)
        two.remove(line1)
    else:
        FO2.write(line1)
for line2 in two:
   FO2.write(line2)

答案 3 :(得分:0)

x=file1.readlines()
y=file2.readlines()    
print list(set(x)&set(y))
#output =['bangalore\n', 'mumbai\n']
a=list(set(x)&set(y))
print list((set(x)|set(y)) - set(a))
#output=['delhi\n', 'chennai\n']