ZIP files

Thomas Heller theller at python.net
Fri Nov 12 06:03:23 EST 2004


aleaxit at yahoo.com (Alex Martelli) writes:

> 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...

I'd suggest to expand this a bit, and make it working correctly on
windows too, where binary files must be opened with the 'b' flag:

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

def write_data(filename, data, flags="wb"):
    _write_data(filename, data, flags)

def write_text(filename, text, flags="w"):
    _write_data(filename, data, flags)

plus the corresponding read_data() and read_text() functions.
Hm, add an encoding for unicode, maybe...
Cookbook recipe, or standard lib?

Thomas



More information about the Python-list mailing list