Search code examples
pythonstringtext-filesglob

Obtaining keyword for matching string in Python


I am writing a script that searches through text files in a directory for certain words. If "True" is returned, then it will print the text file it found it in. Is there a way to return/print the keyword it actually found? Thank you!

from glob import glob

def main():
    directory = "C:\\Files Folder\\*.txt"
    filelist = glob(directory)
    keywords = ("Hello", "Goodbye", "fake")
    for textfile in filelist:
        f = open(textfile, 'r')
        for line in f:
            if any(s in line for s in keywords):
                print "Keyword Found!", f.name

if __name__ == '__main__':
    main()

Solution

  • for line in f:
        for s in keywords:
             if s in line:
                print 'Key word found!', f.name, s