Find entries of one text file in another file in python

99封情书 提交于 2020-01-04 06:12:47

问题


I have two files. File A has some entries in each line and I need to find if any entry is found in File B. Here is my script (using two functions):

def readB(x):
 with open('B.txt') as resultFile:
    for line in resultFile:
        if x in line:
            print x


def readA():
 with open('A.txt') as bondNumberFile:
    for line in bondNumberFile:
        readB(line)

readA()

This script finds the first entry in second file and then does not finds the next one. What might be wrong here?

File A looks like this:

122323 
812549
232335
921020

and File B looks like this:

696798  727832  750478  784201  812549  838916  870906  890988  921020  
697506  727874  751037  784955  813096  838978  872494  891368  921789  
696798  727832  750478  784201  812549  838916  870906  890988  921020  
697506  727874  751037  784955  813096  838978  872494  891368  921789  

回答1:


Strip the entries of newlines

Python includes newlines when you read lines - your first entry is read as 1223232\n. Strip the newline and it will work.

def readA():
    with open('A.txt') as bondNumberFile:
        for line in bondNumberFile:
            readB(line.rstrip())



回答2:


You don't necessarily need to define functions to do this

with open('a.txt') as a, open('b.txt') as b:
    result = set(a.readlines()) & set(b.readlines())

If they both have the same line, it will return them in a set.

If you really wanted a function, you could write it like this

def compare(file1: str, file2: str) -> set:
    with open(file1) as f1, open(file2) as f2:
        return set(f1.readlines()) & set(f2.readlines())


来源:https://stackoverflow.com/questions/37967337/find-entries-of-one-text-file-in-another-file-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!