mahmood
mahmood

Reputation: 24715

Reading words from one file and grep them in another file

I want to pick words from one file and grep them in another file using python. The code looks like

f1 = open("file1.txt",'r')
f2 = open("file2.txt",'r')

def find_word(str, fp):
    for line in fp:
        if line == str:
            print (line)

for word in f1:
    find_word(word, f2)

While I am sure that some words exists in file2.txt, nothing is printed. What is wrong with that snippet?

Upvotes: 0

Views: 207

Answers (2)

tripleee
tripleee

Reputation: 189457

You consume the entire input file the first time you search for a word. Subsequent searches will fail because for line in file will return nothing.

If you are searching for words within a line, that will fail too, because to line you read includes the terminating newline; so

if 'word\n' in line:

will not find word if it is not immediately adjacent to the end of the line.

Upvotes: 1

kopecs
kopecs

Reputation: 1732

Examine the function find_word:

def find_word(str, fp):
    for line in fp:
        if line == str:
            print (line)

This iterates over each line in the file given by fp (or any iterable for that matter). Unless the string str matches a line in the file exactly (including a newline character, if applicable), your function won't print anything. You may want to check if its in that line instead, say with

def find_word(str, fp):
    for line in fp:
        if str in line:
            print (line)

or better yet, as str is a built-in class

def find_word(query, fp):
    for line in fp:
        if query in line:
            print (line)

You also probably want to strip the newline from word in

for word in f1:
    find_word(word, f2)

so instead it might look like

for word in f1:
    find_word(word.rstrip('\r\n'), f2)

Upvotes: 1

Related Questions