When is a directly used file object closed?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • elbin
    New Member
    • Jul 2007
    • 27

    When is a directly used file object closed?

    In the line:

    Code:
    open("file","a").write("\n")
    an object is created, but where does it go afterwards, and is the file "closed" like in:

    Code:
    f = open('file', 'a')
    f.close()
    Is there a problem in not closing files?
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Originally posted by elbin
    In the line:

    Code:
    open("file","a").write("\n")
    an object is created, but where does it go afterwards, and is the file "closed" like in:

    Code:
    f = open('file', 'a')
    f.close()
    Is there a problem in not closing files?
    When reading a file, it is not necessary to create a file object as in:[code=Python]lineList = open('filename' ).readlines()[/code]When writing or appending to a file, I recommend that you create a file object and explicitly close the object when you are through. That forces the system to flush the output buffers and finish writing the data.

    Comment

    • bartonc
      Recognized Expert Expert
      • Sep 2006
      • 6478

      #3
      Originally posted by elbin
      In the line:

      Code:
      open("file","a").write("\n")
      an object is created, but where does it go afterwards, and is the file "closed" like in:

      Code:
      f = open('file', 'a')
      f.close()
      Is there a problem in not closing files?
      Although it is not necessary to explicitly close a file, it is good practice to do so.
      The file will (if all goes well) be closed when the the object is garbage collected.
      If you open a file without keeping a reference to it, there is still an object created which is immediately marked for garbage collection. I cringe when I see people doing this.
      If you do keep a reference as in
      Code:
      f = open('filename')
      then the file will remain open as long as that reference exists.

      Best practice: call close() as soon as you are done with the file.

      Comment

      • ghostdog74
        Recognized Expert Contributor
        • Apr 2006
        • 511

        #4
        Originally posted by elbin
        In the line:

        Code:
        open("file","a").write("\n")
        an object is created, but where does it go afterwards, and is the file "closed" like in:
        yes, its implicitly closed.

        Comment

        Working...