Allowing ref counting to close file items bad style?

Paul Rubin http
Tue Aug 29 22:56:18 EDT 2006


Dan <bounces at foo.org> writes:
> Is this discouraged?:
> 
>      for line in open(filename):
>          <do something with line>

Yes.

> Can I count on the ref count going to zero to close the file?

You really shouldn't.  It's a CPython artifact.

> I understand that the upcoming 'with' statement will obviate this
> question, but how about without 'with'?

   f = open(filename)
try:
   for line in f:
      <do something with line>
finally:
   f.close()



More information about the Python-list mailing list