ZIP files

Alex Martelli aleaxit at yahoo.com
Fri Nov 12 05:27:01 EST 2004


Michael Foord <fuzzyman at gmail.com> wrote:

> Hmmm... does this mean that 
> 
> open(filename, 'w').write(filedata)
> 
> is unsafe ? It's so much more convenient when the object is only going
> to be used for the single action.

It's not exactly unsafe -- but you do risk, depending on what
implementation of Python you're dealing with, that the file object will
just stay open until some unknown time in the future (no later than the
end of your program's run;-).  This may potentially lead to problems if
your program is long-running or open lots of files, etc.

def write_data(filename, data, flags='w'):
    fileobject = open(filename, flags)
    try: fileobject.write(data)
    finally: fileobject.close()

needs to be coded once, and then makes the operation just as convenient
as doing it inline...


Alex



More information about the Python-list mailing list