Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Check list line by line

My problem is following:

def searchWordlist():
path = str(raw_input(PATH))
word = str(raw_input(WORD))
with open(path) as f:
    for line in f:
        if word in line:
            print "Word found"

Than I added following code:

else:
    print "Word not found"

But this obviously can't work, because it will print "Word not found" until the word is found. Well.. but how can I print that the word is not found?! I srsly don't know.

Thank you in advance!

like image 573
Lucas Avatar asked Aug 26 '26 15:08

Lucas


2 Answers

Python has a special trick for this kind of thing:

for line in f:
    if word in line:
        print "Word found"
        break
else:
    print "Word not found"

Here the else goes with the for, and specifically executes if the loop completes normally without hitting a break.

like image 88
Alex Hall Avatar answered Aug 29 '26 07:08

Alex Hall


If all you want it to do is to print whether word is found in any of the lines:

def searchWordlist():    
    path = str(raw_input(PATH))
    word = str(raw_input(WORD))
    with open(path) as f:
        if any(word in line for line in f):
            print('Word found')
        else:
            print('Word not found')
like image 28
user1501961 Avatar answered Aug 29 '26 07:08

user1501961