Allowing ref counting to close file items bad style?

Matthew Woodcraft mattheww at chiark.greenend.org.uk
Wed Aug 30 17:30:33 EDT 2006


Dan  <bounces at foo.org> 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()

One reason to use close() explicitly is to make sure that errors are
reported properly.

If you use close(), an error from the operating system will cause an
exception at a well-defined point in your code. With the implicit
close, an error will probably cause a message to be spewed to stderr
and you might never know about it.

If (as in your example) the file was open for reading only, errors from
close() are unlikely. But I do not think they are guaranteed not to
occur. If you were writing to the file, checking for errors on close()
is indispensable.

-M-




More information about the Python-list mailing list