[Tutor] For loop question
w chun
wescpy at gmail.com
Wed May 10 22:26:57 CEST 2006
> >> 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.
>
> Yes, for writing files I always use an explicit close(), thanks for the
> correction!
those of you who are going to be using 2.5 have this feature automated
for you when using the new 'with' statement: when the 'with' clause
(or suite) finishes, Python will automagically close() your file for
you, read or write, so this is one case you can leave it out.
for example:
---
with open('log.txt', 'w') as f:
:
f.write(...)
:
# f is closed when we get here
---
without going into the details of context managers here for objects to
be used with the 'with' statement, let's just say that an __enter__()
method is called before the block is executed, and an __exit__()
method is called after the suite has completed.
for file objects, file.__exit__ *is* file.close. (for the curious,
this is implemented in Objects/fileobject.c if you've got the 2.5
source.)
looking fwd,
-- 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