user5977290
user5977290

Reputation: 31

Search if line exists from one file to another file

I want to check if content in a is in content b. For each item, I want to check if content in a is located in b(regardless of order).

I can do something like below, but it has to match even the ordering. What's best way to go one by one and print out true if item in a.txt exists in b.txt?

f1 = open("a.txt").read().split("\n")
f2 = open("b.txt").read().split("\n")

for line in f1:
    print f1
for line in f2:
    print f2
print f1 == f2

a.txt

apple
tomato
green
peach
stack
flow
chance

b.txt

stack
peach
blue
green
tomato
wax

result

apple -> false
tomato -> true
green -> true
peach -> true
stack -> true
flow -> false
chance -> false

Upvotes: 0

Views: 3279

Answers (3)

Garrett R
Garrett R

Reputation: 2662

This will work for you.

with open('a.txt') as f, open('b.txt') as g:
        bLines = set([thing.strip() for thing in g.readlines()])
        for line in f:
            line = line.strip()
            if line in bLines:
                print line, "->", "True"
            else:
                print line, "->", "False"

Output

apple -> False
tomato -> True
green -> True
peach -> True
stack -> True
flow -> False
chance -> False

Upvotes: 0

OneCricketeer
OneCricketeer

Reputation: 192043

Regardless of order? Use a set!

with open('a.txt') as f_a, open('b.txt') as f_b:
    a_lines = set(f_a.read().splitlines())
    b_lines = set(f_b.read().splitlines())
for line in a_lines:
    print(line, '->', line in b_lines)

Output

tomato -> True
peach -> True
chance -> False
green -> True
apple -> False
stack -> False
flow -> False

Upvotes: 2

Xiongbing Jin
Xiongbing Jin

Reputation: 12107

for line in f1:
    if line in f2:
        print("true")

Upvotes: -1

Related Questions