try/except with multiple files

Scott David Daniels scott.daniels at acm.org
Sun Jun 24 22:57:16 EDT 2007


bruno.desthuilliers at gmail.com wrote:
> On Jun 21, 9:00 pm, Robert Hicks <sigz... at gmail.com> wrote:
>> Is it good practice to do something like:
>>
>> try:
>>     f1 = file('file1')
>>     f2 = file('file2')
>> except:
>>     # catch the exception
> 
> If what you want is to make sure that resources will be released, you
> can use a try/finally block or (Python 2.5) a with block.

You could do something like this:

     files = []
     try:
         for name in ['abc.txt', 'def.txt', 'ghi.txt']:
             files.append(open(name))
         a, b, c = files
         <code using the three files>
     finally:
         while files:
            files.pop().close()

--Scott David Daniels
scott.daniels at acm.org



More information about the Python-list mailing list