Search code examples
pythonnetworkingscriptinginstancenetmiko

Python: detect if just one of the given words appear in text file


I am trying to get my program to see if one of the 3 words in "words" appears in the fine kal.txt, just the fact that one of the words appear us enough, but I can't seem to get it working.

My Code:

    textring = open('kal.txt', 'r')

    words  =['flapping', 'Unexpected', 'down']
    len_words = len(words)
    print(len_words)

    counter = 0

    while counter < len_words:
        if words[counter] in textring: 
            print('success')
            SAVE_FILE = open('warnings/SW_WARNING.txt', 'w+')
            SAVE_FILE.write(textring)

        counter += 1

This is the output I get in cmd:

    3

That is of course because it's printing the len_words which is 3.

Any suggestions why, or does anyone have a solution?


Solution

  • First we read the file content. Then we loop over each word and check if it is in the text. If it is we write our info and leave the loop.

    with open('kal.txt', 'r') as infile:
        text = infile.read()
    
    words = ['flapping', 'Unexpected', 'down']
    for word in words:
        if word in text:
            print('success')
            with open('warnings/SW_WARNING.txt', 'w+') as save_file:
                save_file.write(text)
            break
    

    Please note the use of the with context manager. When you use with with open there's no need to close the file after the work is done - a task that you forgot to do in your program.

    Additional note: A list is iterable. There's no need to use a counter and access the elements with their index. Working with an index is slower, harder to read and so it is considered "unpythonic". Just loop over the values themselves.