问题
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