file.close()

Carl Banks imbosol at aerojockey.com
Thu Jul 24 06:17:25 CEST 2003


Ben Finney wrote:
> On Wed, 23 Jul 2003 20:29:27 -0700, Erik Max Francis wrote:
>> Bryan wrote:
>>> is what i'm doing is overkill?
>> 
>> Use of external resources -- which should be released as soon as
>> you're done with them -- are best done in try/finally clauses.
> 
> 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?

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(filelist)
    finally:
        for f in filelist:
            f.close()


-- 
CARL BANKS




More information about the Python-list mailing list