[Tutor] Searching a text file's contents and comparing them toalist
alan.gauld at btinternet.com
Wed Jul 14 21:32:10 CEST 2010
"Eric Hamiter" <ehamiter at gmail.com> wrote
> aisle_one = ["chips", "bread", "pretzels", "magazines"]
> aisle_two = ["juice", "ice cream"]
> aisle_three = ["asparagus"]
> def find_groceries():
> grocery_list = open("grocery_list.txt", "r")
> for line in grocery_list.readlines():
See previous about removing the redundant readlines()
> line = line.strip()
> if line in aisle_one:
> first_run = "%s" % line + " - aisle one.\n"
The string formatting is redundant here since you assign a string to a
You could just dio:
first_run = line + " - aisle one.\n"
> I can see that the variables first_run, second_run and third_run are
> writing over themselves while looping, which is logical, but this is
> not what I want. If I simply print them immediately instead of
> them as variables, all items will print, but not in the order I
So store the strings in a list then at the end print each list of
> The ultimate goal of the program will be to sort the items based on
> aisle locations. Is there an efficient way to do this?
You can sort the lists before printing...
> I think I want some kind of incremental counter going on in the loop
> to prevent them from overwriting themselves, or a way to store
> multiple variables, but I'm not sure how to do that.
No need for counters, just append() to a list.
Author of the Learn to Program web site
More information about the Tutor