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

Emile van Sebille emile at fenx.com
Wed Jul 14 18:02:53 CEST 2010


On 7/14/2010 8:46 AM Eric Hamiter said...
> 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:

So it's failing this test.

>         print "success"
>      else:
>         print "no joy"

Try adding some debugging code here, maybe changing the print to:
           print "no joy matching %s" % line

Then read up on readlines and string.strip.

HTH,

Emile




More information about the Tutor mailing list