Q:

Str matching and readlines

I need a script that reads all files in a directory and searches for a keyword in a list of strings. If the keyword is present in the file, then the filename is saved onto a list. Problem is, I am getting sometimes duplicated name files as my files all have 2 lines (1 for title and other for an abstract) and I am searching once in each line - I want to search once for all lines.
This is the code I have as now:
papers = []
files = []
for file in glob.glob("*.txt"):
    with open(file) as f:
        files.append(file)
        for line in f:
            for keyword in keywords:
                if keyword in line:  # search for string
                    print 'found ' + keyword + ' in file %s' % file
                    papers.append(file)
    f.close()

Note: I am aware of list(set(papers)) for eliminating duplicates, but that only works for what I need when I'm only searching for one keyword.
Any help would be appreciated. Thanks 

A:

You can make a variable to check if you've found a match and add a break statement to the end of your if statement. When the condition is met, set the variable to True and break out of the loop. 
Also you don't need f.close() since you are using the with statement.
For example:
papers = []
files = []
for file in glob.glob("*.txt"):
    with open(file) as f:
        files.append(file)
        found_keyword = False
        for line in f:
            for keyword in keywords:
                if keyword in line:  # search for string
                    print 'found ' + keyword + ' in file %s' % file
                    papers.append(file)
                    found_keyword = True
                    break # break out of keyword loop
            if found_keyword:
                break # break out of line loop

