Python 出现在两个单独的txt文件中的行,从一个txt文件中删除

Python 出现在两个单独的txt文件中的行,从一个txt文件中删除,python,python-2.7,Python,Python 2.7,对python来说是个新手。我的问题是,我有一个txt文件('A.txt'),其中有一堆列,还有一个txt文件('B.txt'),其中有不同的数据。但是,B中的一些数据也显示在A中。示例: 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 ...

对python来说是个新手。我的问题是,我有一个txt文件('A.txt'),其中有一堆列,还有一个txt文件('B.txt'),其中有不同的数据。但是,B中的一些数据也显示在A中。示例:

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
...

正如我所说,我已经看过其他类似的问题,并尝试了他们所做的,它给了我这个重复的答案。如有任何建议,将不胜感激

我刚刚复制了你的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

此代码打印行,但如果需要,您也可以将其写入文件

我刚刚复制了您的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

这段代码打印了这一行,但是如果你想,你也可以将它写入一个文件

,因此它只返回154行,我应该得到2044行。(我能够制作一个代码,向我展示有多少重复的代码,这些代码看起来几乎与我提供的代码一模一样)。我认为你的解决方案很接近!所以它只给了我154行,我应该得到2044行。(我能够制作一个代码,向我展示有多少重复的代码,这些代码看起来几乎与我提供的代码一模一样)。我认为你的解决方案很接近!