daniel_e
daniel_e

Reputation: 257

Search for terms in file

I am having problems with my script. I want to find some terms in different files, defined in a searchlist. However - it won't find those terms, even if they are definitely included in those files. I checked it.

Am I missing something?

path = '/mypath'

for filename in glob.glob(os.path.join(path, '*.txt')):
    with open(filename) as infp:
        mylist = infp.read().splitlines() 
        for word in mylist:
            searchlist = ["term1", "term2", "term3"]
            for i in searchlist:
                if i in word:
                    print ('found')
                else: 
                    print ('not found')

Upvotes: 0

Views: 30

Answers (1)

Rakesh
Rakesh

Reputation: 82755

This might help

path = '/mypath'

for filename in glob.glob(os.path.join(path, '*.txt')):
    with open(filename) as infp:
        data = infp.read()    #Just Read the content
        searchlist = ["term1", "term2", "term3"]
        for i in searchlist:
            if i in data:  #Check if search term in content. 
                print('found')
            else: 
                print('not found')

Upvotes: 1

Related Questions