file.close()

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

    file.close()

    i'm curious to know how others handle the closing of files. i seem to
    always end up with this pattern even though i rarely see others do it.

    f1 = file('file1')
    try:
    # process f1
    finally:
    f1.close()

    which explicitly closes f1

    or for multiple files:

    f1 = file('file1')
    try:
    f2 = file('file2')
    try:
    # process f1 & f2
    finally:
    f2.close()
    finally:
    f1.close()

    which explicitly closes f1 & f2
    any exceptions opening f1 or f2 is handled outside of this structure or is
    allowed to fall out of the program. i'm aware that files will automatically
    be closed when the process exits. i'm just curious how others do this for
    small scripts and larger programs. is what i'm doing is overkill?

    thanks,

    bryan


  • Erik Max Francis

    #2
    Re: file.close()

    Bryan wrote:
    [color=blue]
    > which explicitly closes f1 & f2
    > any exceptions opening f1 or f2 is handled outside of this structure
    > or is
    > allowed to fall out of the program. i'm aware that files will
    > automatically
    > be closed when the process exits. i'm just curious how others do this
    > for
    > small scripts and larger programs. is what i'm doing is overkill?[/color]

    No, not at all; it's safe and portable. Python the language does not
    specify when objects get reclaimed, although CPython the implementation
    does it promptly. Use of external resources -- which should be released
    as soon as you're done with them -- are best done in try/finally
    clauses.

    --
    Erik Max Francis && max@alcyone.com && http://www.alcyone.com/max/
    __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
    / \ It is fatal to enter any war without the will to win it.
    \__/ Douglas MacArthur

    Comment

    • Ben Finney

      #3
      Re: file.close()

      On Wed, 23 Jul 2003 20:29:27 -0700, Erik Max Francis wrote:[color=blue]
      > Bryan wrote:[color=green]
      >> is what i'm doing is overkill?[/color]
      >
      > Use of external resources -- which should be released as soon as
      > you're done with them -- are best done in try/finally clauses.[/color]

      It seems that nesting the 'try' clauses doesn't scale well. What if
      fifty files are opened? Must the nesting level of the 'try' clauses be
      fifty also, to close them promptly?

      --
      \ "God forbid that any book should be banned. The practice is as |
      `\ indefensible as infanticide." -- Dame Rebecca West |
      _o__) |
      http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B

      Comment

      • Erik Max Francis

        #4
        Re: file.close()

        Ben Finney wrote:
        [color=blue]
        > It seems that nesting the 'try' clauses doesn't scale well. What if
        > fifty files are opened? Must the nesting level of the 'try' clauses
        > be
        > fifty also, to close them promptly?[/color]

        If you're manipulating fifty files in one block, presumably you're doing
        so in a uniform way:

        allFiles = [...]
        try:
        ...
        finally:
        for eachFile in allFiles:
        eachFile.close( )

        --
        Erik Max Francis && max@alcyone.com && http://www.alcyone.com/max/
        __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
        / \ Man is a hating rather than a loving animal.
        \__/ Rebecca West

        Comment

        • Carl Banks

          #5
          Re: file.close()

          Ben Finney wrote:[color=blue]
          > On Wed, 23 Jul 2003 20:29:27 -0700, Erik Max Francis wrote:[color=green]
          >> Bryan wrote:[color=darkred]
          >>> is what i'm doing is overkill?[/color]
          >>
          >> Use of external resources -- which should be released as soon as
          >> you're done with them -- are best done in try/finally clauses.[/color]
          >
          > It seems that nesting the 'try' clauses doesn't scale well. What if
          > fifty files are opened? Must the nesting level of the 'try' clauses be
          > fifty also, to close them promptly?[/color]

          If you need 50 open files, you almost certainly want to have a way of
          organizing them. Probably they'll be in a list or dictionary. So, if
          they're in a list, for example, you can do this:


          filelist = []
          try:
          filelist.append (open(filename[0]))
          filelist.append (open(filename[1]))
          ...
          do_something(fi lelist)
          finally:
          for f in filelist:
          f.close()


          --
          CARL BANKS

          Comment

          • Ben Finney

            #6
            Re: file.close()

            Bryan (original poster) wrote:[color=blue]
            > f1 = file('file1')
            > try:
            > f2 = file('file2')
            > try:
            > # process f1 & f2
            > finally:
            > f2.close()
            > finally:
            > f1.close()[/color]


            On Wed, 23 Jul 2003 21:12:34 -0700, Erik Max Francis wrote:[color=blue]
            > Ben Finney wrote:[color=green]
            >> It seems that nesting the 'try' clauses doesn't scale well. What if
            >> fifty files are opened? Must the nesting level of the 'try' clauses
            >> be fifty also, to close them promptly?[/color]
            >
            > If you're manipulating fifty files in one block, presumably you're
            > doing so in a uniform way:
            >
            > allFiles = [...]
            > try:
            > ...
            > finally:
            > for eachFile in allFiles:
            > eachFile.close( )[/color]

            This doesn't match Bryan's nested structure above, which you blessed as
            not "overkill" (in his words). It was this that I considered a
            poorly-scaling structure, or "overkill" since only one 'try' block is
            required. Do you disagree?

            --
            \ "Too many Indians spoil the golden egg." -- Sir Joh |
            `\ Bjelke-Petersen |
            _o__) |
            http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B

            Comment

            • Erik Max Francis

              #7
              Re: file.close()

              Ben Finney wrote:
              [color=blue]
              > This doesn't match Bryan's nested structure above, which you blessed
              > as
              > not "overkill" (in his words). It was this that I considered a
              > poorly-scaling structure, or "overkill" since only one 'try' block is
              > required. Do you disagree?[/color]

              It uses try/finally to secure the closing of many files in a timely
              manner. In that sense, it certainly fits the pattern. It doesn't have
              the same nested pattern, but try/finally isn't at issue here. If you
              had code which opened 50 files and looked like:

              fileOne = file(...)
              fileTwo = file(...)
              fileThree = file(...)
              ...
              fileFortyNine = file(...)
              fileFifty = file(...)

              I would say you are doing something wrong. A more systematic handling
              of many, many files is indicated whether or not you're using the
              try/finally idiom to ensure files get closed in a timely manner.

              --
              Erik Max Francis && max@alcyone.com && http://www.alcyone.com/max/
              __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
              / \ Together we can take this one day at a time
              \__/ Sweetbox

              Comment

              • Bryan

                #8
                Re: file.close()

                >[color=blue]
                > If you need 50 open files, you almost certainly want to have a way of
                > organizing them. Probably they'll be in a list or dictionary. So, if
                > they're in a list, for example, you can do this:
                >
                >
                > filelist = []
                > try:
                > filelist.append (open(filename[0]))
                > filelist.append (open(filename[1]))
                > ...
                > do_something(fi lelist)
                > finally:
                > for f in filelist:
                > f.close()
                >[/color]


                erik, carl... thanks... this is exactly what i was looking for

                bryan


                Comment

                • Ben Finney

                  #9
                  Re: file.close()

                  On Thu, 24 Jul 2003 05:20:15 GMT, Bryan wrote:[color=blue][color=green]
                  >> filelist = []
                  >> try:
                  >> filelist.append (open(filename[0]))
                  >> filelist.append (open(filename[1]))
                  >> ...
                  >> do_something(fi lelist)
                  >> finally:
                  >> for f in filelist:
                  >> f.close()[/color]
                  >
                  > erik, carl... thanks... this is exactly what i was looking for[/color]

                  The only substantial difference I see between this and what you
                  originally posted, is that there is only one 'try...finally' block for
                  all the file open/close operations. Is this what you were wanting
                  clarified?

                  --
                  \ "I spent all my money on a FAX machine. Now I can only FAX |
                  `\ collect." -- Steven Wright |
                  _o__) |
                  http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B

                  Comment

                  • Bryan

                    #10
                    Re: file.close()


                    "Ben Finney" <bignose-hates-spam@and-benfinney-does-too.id.au> wrote in
                    message news:slrnbhusl6 .13c.bignose-hates-spam@iris.polar .local...[color=blue]
                    > On Thu, 24 Jul 2003 05:20:15 GMT, Bryan wrote:[color=green][color=darkred]
                    > >> filelist = []
                    > >> try:
                    > >> filelist.append (open(filename[0]))
                    > >> filelist.append (open(filename[1]))
                    > >> ...
                    > >> do_something(fi lelist)
                    > >> finally:
                    > >> for f in filelist:
                    > >> f.close()[/color]
                    > >
                    > > erik, carl... thanks... this is exactly what i was looking for[/color]
                    >
                    > The only substantial difference I see between this and what you
                    > originally posted, is that there is only one 'try...finally' block for
                    > all the file open/close operations. Is this what you were wanting
                    > clarified?
                    >[/color]

                    well, it wasn't exactly clarification as much as seeing another more
                    scalable solution. i know a lot of people don't explicitly close files in
                    python, but i always do even for small scripts.

                    thanks again,

                    bryan


                    Comment

                    • Ben Finney

                      #11
                      Re: file.close()

                      On Wed, 23 Jul 2003 22:19:07 -0700, Erik Max Francis wrote:[color=blue]
                      > Ben Finney wrote:[color=green]
                      >> This doesn't match Bryan's nested structure above, which you blessed
                      >> as not "overkill" (in his words).[/color]
                      > It doesn't have the same nested pattern, but try/finally isn't at
                      > issue here.[/color]

                      Judging by Bryan's responses elsewhere in this thread, the multiple
                      nested 'try...finally' is indeed what he was asking about. The question
                      seems to be answered now.

                      --
                      \ "Those who will not reason, are bigots, those who cannot, are |
                      `\ fools, and those who dare not, are slaves." -- "Lord" George |
                      _o__) Gordon Noel Byron |
                      http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B

                      Comment

                      • Francois Pinard

                        #12
                        Re: file.close()

                        [Bryan]
                        [color=blue]
                        > I'm curious to know how others handle the closing of files. [...] I'm
                        > aware that files will automatically be closed when the process exits.[/color]

                        For one, I systematically avoid cluttering my code with unneeded `close'.
                        The advantages are simplicity and legibility, both utterly important to me.

                        However, I do understand that if I ever have to move a Python script
                        to Jython, I will have to revise my scripts for adding the clutter I am
                        sparing today. I'm quite accepting to do that revision if this occurs.
                        Until then, I prefer keeping my scripts as neat as possible.

                        For me, explicitely closing a file, for which the only reference is about
                        to disappear through function exiting, would be very similar to using
                        `del' on any variable I happened to use in that function: gross overkill...

                        The only reason to call `close' explicitly is when there is a need to close
                        prematurely. Absolutely no doubt that such needs exist at times. But
                        closing all the time "just in case" is symptomatic of unsure programming.
                        Or else, it is using Python while still thinking in other languages.

                        --
                        François Pinard http://www.iro.umontreal.ca/~pinard

                        Comment

                        • Bryan

                          #13
                          Re: file.close()


                          "Francois Pinard" <pinard@iro.umo ntreal.ca> wrote in message
                          news:mailman.10 59052897.16526. python-list@python.org ...[color=blue]
                          > [Bryan]
                          >[color=green]
                          > > I'm curious to know how others handle the closing of files. [...] I'm
                          > > aware that files will automatically be closed when the process exits.[/color]
                          >
                          > For one, I systematically avoid cluttering my code with unneeded `close'.
                          > The advantages are simplicity and legibility, both utterly important to[/color]
                          me.[color=blue]
                          >
                          > However, I do understand that if I ever have to move a Python script
                          > to Jython, I will have to revise my scripts for adding the clutter I am
                          > sparing today. I'm quite accepting to do that revision if this occurs.
                          > Until then, I prefer keeping my scripts as neat as possible.
                          >
                          > For me, explicitely closing a file, for which the only reference is about
                          > to disappear through function exiting, would be very similar to using
                          > `del' on any variable I happened to use in that function: gross[/color]
                          overkill...[color=blue]
                          >
                          > The only reason to call `close' explicitly is when there is a need to[/color]
                          close[color=blue]
                          > prematurely. Absolutely no doubt that such needs exist at times. But
                          > closing all the time "just in case" is symptomatic of unsure programming.
                          > Or else, it is using Python while still thinking in other languages.
                          >
                          > --
                          > François Pinard http://www.iro.umontreal.ca/~pinard
                          >[/color]

                          you are correct this is so awesome... at least for me it is... now i remove
                          a lot of my clutter too :) i just did some tests on windows by trying to
                          delete file1 at the command prompt when raw_input is called.

                          f = file('file1')
                          raw_input('paus e')

                          ### the file is NOT closed


                          file('file1')
                          raw_input('paus e')

                          ### the file IS closed


                          f = file('file1')
                          del f
                          raw_input('paus e')

                          ### the file IS closed


                          def foo():
                          f = file('file1')

                          foo()
                          raw_input('paus e')

                          ### the file IS closed



                          can you explain to me how the file gets closed? i'm sure that garbage
                          collection hasn't happed at the point that i call raw_input. it must have
                          something to do with the reference count of the file object. does python
                          immediately call close for you when the reference count goes to zero? i
                          want the dirty details...

                          thanks,

                          bryan


                          Comment

                          • Ulrich Petri

                            #14
                            Re: file.close()


                            "Francois Pinard" <pinard@iro.umo ntreal.ca> schrieb im Newsbeitrag
                            news:mailman.10 59052897.16526. python-list@python.org ...[color=blue]
                            > [Bryan]
                            >[color=green]
                            > > I'm curious to know how others handle the closing of files. [...] I'm
                            > > aware that files will automatically be closed when the process exits.[/color]
                            >
                            > For one, I systematically avoid cluttering my code with unneeded `close'.
                            > The advantages are simplicity and legibility, both utterly important to[/color]
                            me.[color=blue]
                            >
                            > However, I do understand that if I ever have to move a Python script
                            > to Jython, I will have to revise my scripts for adding the clutter I am
                            > sparing today. I'm quite accepting to do that revision if this occurs.
                            > Until then, I prefer keeping my scripts as neat as possible.
                            >
                            > For me, explicitely closing a file, for which the only reference is about
                            > to disappear through function exiting, would be very similar to using
                            > `del' on any variable I happened to use in that function: gross[/color]
                            overkill...[color=blue]
                            >
                            > The only reason to call `close' explicitly is when there is a need to[/color]
                            close[color=blue]
                            > prematurely. Absolutely no doubt that such needs exist at times. But
                            > closing all the time "just in case" is symptomatic of unsure programming.
                            > Or else, it is using Python while still thinking in other languages.
                            >[/color]

                            fire up your python and type: "import this" read the output and rethink your
                            codint techniques

                            Ciao Ulrich


                            Comment

                            • Erik Max Francis

                              #15
                              Re: file.close()

                              Bengt Richter wrote:
                              [color=blue]
                              > 1) Is f.done() really necessary? I.e., doesn't an explicit del f take
                              > care of it
                              > if the object has been coded with a __del__ method? I.e., the idea
                              > was to get
                              > the effect of CPython's immediate effective del on ref count going
                              > to zero, right?[/color]

                              It wouldn't if there were circular references at that point. If you're
                              going to have some kind of `with' structure that constraints lifetimes,
                              I'd think you'd probably want something more concrete than just object
                              deletion; you'd want to make sure a "Stop whatever you were doing now"
                              method were present and called. But maybe that really depends on the
                              primary thing that the `with' construct would be used for.

                              --
                              Erik Max Francis && max@alcyone.com && http://www.alcyone.com/max/
                              __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
                              / \ Love is when you wake up in the morning and have a big smile.
                              \__/ Anggun

                              Comment

                              Working...