2017-02-17 59 views
1

蟒蛇很新。我的问题是,我有一个txt文件('A.txt'),其中有一堆列和第二个txt文件('B.txt)具有不同的数据。然而,一些在B中的数据也显示在A.例:行出现在两个单独的txt文件,从一个txt文件中删除

A.txt: 

name1 x1 y1 
name2 x2 y2 
name3 x3 y3 
name4 x4 y4 
name5 x5 y5 
name6 x6 y6 
... 

B.txt 
namea xa ya 
name2 x2 y2 
name3 x3 y3 
nameb xb yb 
namec xc yc 
... 

我想在B.txt一切,显示了在A.TXT从A.TXT 删除我意识到这有之前曾被问过,但我已经尝试过给人们提出类似问题的建议,但这对我不起作用。

到目前为止,我有:

tot = 0 
with open('B.txt', 'r') as f1: 
    for a in f1: 
     WR = a.strip().split() 

     with open('A.txt', 'r+') as f2: 
      for b in f2: 
       l = b.strip().split() 

       if WR not in l: 
        print l 
        tot += 1 

       #I've done it the following way and also doesn't give the  
       #output I need 
       #if WR == l: #find duplicates 
       # continue 
       #else: 
       # print l 
print tot 

当我运行此我的东西拿回来,我认为答案是(文件A有2060文件B具有154),但重复154次。 所以,例如我的意思是:

A.txt: 
name1 x1 y1 
name4 x4 y4 
name5 x5 y5 
name6 x6 y6 
... 
name1 x1 y1 
name4 x4 y4 
name5 x5 y5 
name6 x6 y6 
...  
name1 x1 y1 
name4 x4 y4 
name5 x5 y5 
name6 x6 y6 
... 
name1 x1 y1 
name4 x4 y4 
name5 x5 y5 
name6 x6 y6 
... 

我只希望它看起来像:

A.txt: 
name1 x1 y1 
name4 x4 y4 
name5 x5 y5 
name6 x6 y6 
... 

就像我说的,我已经看过其他类似的问题,并试图什么他们做了,并且给了我这个重复的答案。任何建议将不胜感激!

回答

0

我只是复制你的A和B文件所以只是检查,让我知道,如果它的正确

tot = 0 
f1 = open('B.txt', 'r') 
f2 = open('A.txt', 'r') 

lista = [] 
for line in f1: 
    line.strip() 
    lista.append(line) 

listb = [] 
for line in f2: 
    line.strip() 
    listb.append(line) 

for b in listb: 
    if b in lista: 
     continue 
    else: 
     print(b) 
     tot+=1 

此代码打印行,但如果你愿意,你可以写一个文件也

+0

所以它只给了我154行代码,而且我应该得到2044代码。(我能够创建一个代码,告诉我有多少副本,看起来几乎和我提供的代码差不多)。我认为你的解决方案非常接近! – aaa343

+0

检查修改后的代码,这是你需要的吗? –