[Tutor] For loop question

w chun wescpy at gmail.com
Wed May 10 16:59:21 CEST 2006


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

yup, that's why i mention this fact below while giving the genex solution.


> > 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().

i'm still not comfortable without doing my own explicit close(), esp.
for writing to files... maybe i'm just used to malloc/new-free pairs
like i am with open-close, although on the other hand, getting rid of
another line of code is tempting -- so i will actually do this with a
short piece of code that is read-only.

note for the uninitiated, open() == file(), or rather, open == file, or rather:

>>> open is file
True

-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com


More information about the Tutor mailing list