Q on explicitly calling file.close

r rt8396 at gmail.com
Thu Sep 10 00:13:49 CEST 2009

On Sep 9, 4:19 pm, Charles Yeomans <char... at declareSub.com> wrote:
> Unfortunately, both of these simple templates have the following  
> problem -- if open fails, a NameError will be raised from the finally  
> block.

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

how will the caller know an exception has occurred? What if logic
depends on the validation that a file *had* or *had not* been written
too, huh?

> 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

Oh I see! But what happens if the filename does not exist? What then?
"open" will blow chucks thats what! Here is a version for our paranoid-
schizophrenic-sadomasochist out there...

def egor_read_file(fname, mode='rb'):
    print 'yes, master'
	f = open(fname, mode=mode)
    except IOError:
        return (0, 'But, the file no open master!')

        s = f.read()
    except NameError:
        return (0, 'the file still no open master!')

        print 'That file sure is tricky master!

    return (s, 'Whew! here is the file contents, master')

> MRAB wrote:
> You should've used raw strings. :-)

rats!, you got me on that one :-)

free beer tomorrow @ http://jjsenlightenments.blogspot.com/

More information about the Python-list mailing list