Q on explicitly calling file.close

kj no.email at please.post
Sun Sep 6 03:51:50 CEST 2009


In <02b2e6ca$0$17565$c3e8da3 at news.astraweb.com> Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> writes:

>(3) For quick and dirty scripts, or programs that only use one or two 
>files, relying on the VM to close the file is sufficient (although lazy 
>in my opinion *wink*)

It's not a matter of laziness or industriousness, but rather of
code readability.  The real problem here is not the close() per
se, but rather all the additional machinery required to ensure that
the close happens.  When the code is working with multiple file
handles simultaneously, one ends up with a thicket of try/finally's
that makes the code just *nasty* to look at.  E.g., even with only
two files, namely an input and an output file, compare:

def nice(from_, to_):
    to_h = file(to_, "w")
    for line in file(from_):
        print >> to_h, munge(line)

def nasty(from_, to_):
    to_h = file(to_, "w")
    try:
        from_h = file(from_)
        try:
             for line in from_h:
                 print >> to_h, munge(line)
        finally:
            from_h.close()
    finally:
        to_h.close()

I leave to your imagination the joys of reading the code for
hairy(from_, to_, log_), where log_ is a third file to collect
warning messages.

kynn



More information about the Python-list mailing list