[Tutor] For loop question

Kent Johnson kent37 at tds.net
Wed May 10 11:52:14 CEST 2006


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



More information about the Tutor mailing list