[Tutor] For loop question

Kent Johnson kent37 at tds.net
Wed May 10 14:55:56 CEST 2006


Smith, Jeff wrote:
> At least with Python there's only one obvious way to do something :-)

Yeah, right. A couple of minutes reading comp.lang.python will disabuse 
you of that notion :-)
> 
> 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())

If you are willing to depend on the runtime to close the file that is 
fine. If you want to close it yourself you have to keep a reference to 
the open file.

For short Python scripts I usually allow the runtime to close the file. 
For longer programs and anything written in Jython (which has different 
garbage collection behaviour) I usually use an explicit close().

Kent

> 
> 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