Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

string - 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  
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...