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

Alan Gauld alan.gauld at btinternet.com
Wed Jul 14 19:26:56 CEST 2010


"Eric Hamiter" <ehamiter at gmail.com> wrote

> Fantastic! I have this, which now works. Is there a better place to 
> put
> string.strip?

Its largely a matter of taste and how you intend using the value.

> aisle_one = ["chips", "bread", "pretzels", "magazines"]
>
> grocery_list = open("grocery_list.txt", "r")
> for line in grocery_list.readlines():

You could improve that with

for line in open('grocery_list.txt'):

ie no need for readlines()

Or if using recent(post 2.5) versions of Python you could use with:

with open('grocery_list.txt') as grocery_list:
      for line in grocery_list:

which will ensure the file is closed correctly without you
having to do it yourself. This is probably the best option.

>    if line.strip() in aisle_one:
>       print "success! i found %s" % line

If you never need a stripped version of line again, or if you
are planning on writing it out to another file then this is fine.
If you are going to use it again its probably better to strip()
and asign to itelf:

line = line.strip()

Also you might find rstrip() slightly safer if you have any
unusual characters at the start of line...

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list