[Tutor] Searching a text file's contents and comparing them to a list

Eric Hamiter ehamiter at gmail.com
Wed Jul 14 17:46:20 CEST 2010


Hi all,

New programmer here. This is what I want to do:

1. Open an existing text file named "grocery_list.txt", which has one
item per line, like so:

butter
juice
bread
asparagus
magazines
ice cream

2. ...and search for these items in a pre-defined list.

But I can't seem to get this working. Right now after trying the following:


aisle_one = ["chips", "bread", "pretzels", "magazines"]

grocery_list = open("grocery_list.txt", "r")
for line in grocery_list.readlines():
    if line in aisle_one:
       print "success"
    else:
       print "no joy"
grocery_list.close()


I get this:

no joy
no joy
no joy
no joy
no joy
no joy

when I'm expecting this:

no joy
no joy
success
no joy
success
no joy


Am I close? This seems like it should work but I'm obviously missing something.

Thanks,

Eric


More information about the Tutor mailing list