Temporary Files

Tony Meyer ta-meyer at ihug.co.nz
Wed Apr 30 01:53:19 EDT 2003


I need to update a file - I need to write the new version to a temp
file, and then remove the old version and replace it with the new one.
This is what I'm doing at the moment:

>>> import shutil
>>> import tempfile
>>> out = tempfile.TemporaryFile("w")
>>> out.write(data)
>>> out.flush()
>>> shutil.copyfile(out.name, permanent_name)
>>> out.close()

This works fine on Windows, but on (some, at least) linuxes it fails
because out.name doesn't give the correct name.

Could someone point me towards the right way of doing this?  I realise I
can just do:
>>> out = file(tempfile.mktemp())
but it seems from the documentation that TemporaryFile is the better
method.

Is there perhaps a different method of copying?  One that doesn't take
filenames, but file objects?

I've tried googling, but everything just comes up with guff about
security flaws in Python temp files...

TIA.

=Tony Meyer






More information about the Python-list mailing list