Skip to content Skip to sidebar Skip to footer

Python - Search Text File For Any String In A List

Apologies is this is against the rules. I have tried creating a simple Python script that searches a text file for any of the strings in a list. KeyWord =['word', 'word1', 'word3']

Solution 1:

You could do this with a for loop as below. The issue with your code is it does not know what x is. You can define it inside of the loop to make x equal to a value in the KeyWord list for each run of the loop.

KeyWord =['word', 'word1', 'word3']
withopen('Textfile.txt', 'r') as f:
    read_data = f.read()
for x in KeyWord:
    if x in read_data:
        print('True')

Solution 2:

x is not defined. You forgot the loop that would define it. This will create a generator so you will need to consume it with any:

KeyWord =['word', 'word1', 'word3']

if any(x inopen('Textfile.txt').read() for x in KeyWord):
    print('True')

This works but it will open and read the file multiple times so you may want

KeyWord = ['word', 'word1', 'word3']

file_content = open('test.txt').read()

if any(x in file_content for x in KeyWord):
    print('True')

This also works, but you should prefer to use with:

KeyWord = ['word', 'word1', 'word3']

withopen('test.txt') as f:
    file_content = f.read()

ifany(x in file_content for x in KeyWord):
    print('True')

All of the above solutions will stop as soon as the first word in the list is found in the file. If this is not desireable then

KeyWord = ['word', 'word1', 'word3']

withopen('test.txt') as f:
    file_content = f.read()

for x in KeyWord:
    if x in file_content:
        print('True')

Post a Comment for "Python - Search Text File For Any String In A List"