Q on explicitly calling file.close

Charles Yeomans charles at declareSub.com
Wed Sep 9 23:19:29 CEST 2009


On Sep 9, 2009, at 4:50 PM, r wrote:

> On Sep 9, 3:18 pm, David C Ullrich <dullr... at sprynet.com> wrote:
> (snip)
>> These days I've actually got the syntax and spelling memorized -
>> I can type "close()" without needing to look it up!
>
> +1
>
> You are so right David! I think some people around here need to look
> up "code reuse". Here are a couple of simple templates for our friends
> to study...
>
> def read_file(fname, mode='rb'):
>    '''open file and return contents'''
>    try:
>        f = open(fname, mode)
>        s = f.read()
>        return s
>    except:
>        return 0
>    finally:
>        f.close()
>
> def write_file(fname, s, mode='wb'):
>    '''open file, truncate, and write string'''
>    try:
>        f = open(fname, mode)
>        f.write(s)
>        return 1
>    except:
>        return 0
>    finally:
>        f.close()


Unfortunately, both of these simple templates have the following  
problem -- if open fails, a NameError will be raised from the finally  
block.


def read_file(fname, mode='rb'):
    '''open file and return contents'''
    f = open(fname, mode)
    try:
        return f.read()

    finally:
        f = f.close()

I removed the except block because I prefer exceptions to error codes.

def write_file(fname, s, mode='wb'):
    '''open file, truncate, and write string'''
    f = open(fname, mode)
    try:
        f.write(s)

    finally:
        f = f.close()

In addition to fixing the latent bug in the second simple template, I  
took the opportunity to correct your heinous violation of command- 
query separation.


Charles Yeomans




More information about the Python-list mailing list