Welcome, guest | Sign In | My Account | Store | Cart
from contextlib import contextmanager
import os, binascii

@contextmanager
def replacefile(name):
    tmpname = '%s.tmp-%s' % (name, binascii.hexlify(os.urandom(10)).decode('ascii'))
    try:
        with open(tmpname, 'w+') as f:
            yield f
            os.rename(tmpname, name)
    finally:
        try:
            os.unlink(tmpname)
        except OSError:
            pass

Diff to Previous Revision

--- revision 1 2012-06-17 09:15:55
+++ revision 2 2012-06-17 11:55:57
@@ -7,8 +7,6 @@
     try:
         with open(tmpname, 'w+') as f:
             yield f
-            if not f.closed:
-                raise RuntimeError('replacefile() not closed')
             os.rename(tmpname, name)
     finally:
         try:

History