Search code examples
pythonstringcomparereadfile

Find entries of one text file in another file in python


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  

Solution

  • 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())