0

I have a folder with lots of files, some of them contain one or several keywords, I also have a separate file, consisting of keywords only, a word per line, like this:

keyword1
keyword2
keyword3

I need to find all of these files.

So I have this code

import os

directory = os.listdir("D:/where_2_search")

with open('what_2search.txt','r') as searchlist:
    for line in searchlist:
    print(line)
    for fname in directory:
        if os.path.isfile("D:/where_2_search" + os.sep + fname):
            searchedfile = open("D:/where_2_search" + os.sep + fname, 'r')
            if line in searchedfile.read():
                print('found string in file %s' % fname)
            else:
                print('string not found')
            searchedfile.close()

But it doesn't work as I receive negative results only. How could I fix it?

1
  • this could just be in the sample, but watch your indentation Commented Nov 19, 2017 at 1:38

2 Answers 2

1

I think the best module to use is glob. You can simply read the keywords from file and get list of files that matches the keywords.

NOTE Not tested. I recommend you to do yourself. This is just a help/overview.

from glob import glob
import os

with open('what_2search.txt','r') as searchlist:
    keywords= searchlist

found_files = []
# You might want to change the working directory as follow if needed
os.chdir(path_where_those_files_are)
for keyword in keywords:
    found_files.append(glob(keyword)) # Here is a little bug. But can easily sort this out

print(found_files) # List of files needed
Sign up to request clarification or add additional context in comments.

Comments

0

You have newlines at the end of your keywords

try changing to this

if line.rstrip() in searchedfile.read():

2 Comments

Doesn't change a thing, sory.
Strange. I've verified it fixes the issue on my system.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.