file.close()

Bryan belred1 at yahoo.com
Wed Jul 23 23:17:30 EDT 2003


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






More information about the Python-list mailing list