Open and closing files

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Thomas Ploch

    #1

    Open and closing files

    Is it defined behaviour that all files get implicitly closed when not
    assigning them?

    Like:

    def writeFile(fName , foo):
    open(fName, 'w').write(proc ess(foo))

    compared to:


    def writeFile(fName , foo):
    fileobj = open(fName, 'w')
    fileobj.write(p rocess(foo))
    fileobj.close()

    Which one is the 'official' recommended way?

    Thomas
  • John Machin

    #2
    Re: Open and closing files


    Thomas Ploch wrote:
    Is it defined behaviour that all files get implicitly closed when not
    assigning them?
    >
    Like:
    >
    def writeFile(fName , foo):
    open(fName, 'w').write(proc ess(foo))
    >
    compared to:
    >
    >
    def writeFile(fName , foo):
    fileobj = open(fName, 'w')
    fileobj.write(p rocess(foo))
    fileobj.close()
    >
    Which one is the 'official' recommended way?
    No such thing as an 'official' way.

    Nothing happens until the file object is garbage-collected. GC is
    generally not under your control.

    Common sense suggests that
    (a) when you are reading multiple files, you close each one explicitly
    (b) when you are writing a file, you close it explicitly as soon as you
    are done with it. That way you can trap any error condition and do
    something moderately sensible -- better than getting an error condition
    during GC when your Python process is shutting down.

    HTH,
    John

    Comment

    • tleeuwenburg@gmail.com

      #3
      Re: Open and closing files


      John Machin wrote:
      Thomas Ploch wrote:
      Is it defined behaviour that all files get implicitly closed when not
      assigning them?

      Like:

      def writeFile(fName , foo):
      open(fName, 'w').write(proc ess(foo))

      compared to:


      def writeFile(fName , foo):
      fileobj = open(fName, 'w')
      fileobj.write(p rocess(foo))
      fileobj.close()

      Which one is the 'official' recommended way?
      >
      No such thing as an 'official' way.
      >
      Nothing happens until the file object is garbage-collected. GC is
      generally not under your control.
      >
      Common sense suggests that
      (a) when you are reading multiple files, you close each one explicitly
      (b) when you are writing a file, you close it explicitly as soon as you
      are done with it. That way you can trap any error condition and do
      something moderately sensible -- better than getting an error condition
      during GC when your Python process is shutting down.
      >
      HTH,
      John
      Not to mention you can get bitten on the ass by a few characters
      sitting in a buffer someplace when you expect your file to have been
      fully written.

      Close the thing.

      Cheers,
      -T

      Comment

      Working...