[Tutor] For loop question

Smith, Jeff jsmith at medplus.com
Wed May 10 14:42:47 CEST 2006


At least with Python there's only one obvious way to do something :-)

I'll see your simplification and raise (or lower) you a line.

Why not simply:

for item in file('hosts.txt'):
     tn = telnetlib.Telnet(item.strip())

Jeff

-----Original Message-----
From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On
Behalf Of Kent Johnson
Sent: Wednesday, May 10, 2006 5:52 AM
Cc: tutor at python.org
Subject: Re: [Tutor] For loop question


w chun wrote:
> another thing is that if the host file is large, you may wish to 
> iterate through the file one line at a time with a list comprehension 
> to do the stripping for you:
> 
> HostFile = open("hosts.txt", 'r')
> for item in [x.strip() for x in HostFile]:
>         :

Why is this better when the file is large? It still creates a list with 
all lines in it.
> 
> if you are using Python 2.4+, you can come up with an even better 
> solution by using a generator expression that does lazier, ad hoc
> evaluation:
> 
> HostFile = open("hosts.txt", 'r')
> for item in (x.strip() for x in HostFile):
>         :
> 
> this one will read and strip one line from the file as you process it 
> while the previous solution still needs to come up with the entire 
> list of stripped hosts before the for-loop can begin.

I would use this, it avoids reading the entire file at once and IMO is 
clear and straightforward:
HostFile = open('hosts.txt')
for item in HostFile:
     item = item.strip()
     ...

or even
HostFile = open('hosts.txt')
for item in HostFile:
     tn = telnetlib.Telnet(item.strip())
     ...

Kent

_______________________________________________
Tutor maillist  -  Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor


More information about the Tutor mailing list