Allowing ref counting to close file items bad style?

Fredrik Lundh fredrik at pythonware.com
Wed Aug 30 01:43:24 EDT 2006


Dan wrote:

> Is this discouraged?:
> 
>      for line in open(filename):
>          <do something with line>
> 
> That is, should I do this instead?:
> 
>      fileptr = open(filename)
>      for line in fileptr:
>          <do something with line>
>      fileptr.close()

depends on the use case; in a small program that you know will only read 
a few files, you can leave it to the system (especially on CPython).  if 
you're about to process large number of files, or you're writing files, 
it's usually better to be explicit.

note that to be really safe, you should use try/finally:

     f = open(filename)
     try:
         f.write(...)
     finally:
         f.close()

</F>




More information about the Python-list mailing list