import ctypes windll = ctypes.windll MOVEFILE_REPLACE_EXISTING = 0x1 MOVEFILE_WRITE_THROUGH = 0x8 MoveFileTransacted = windll.kernel32.MoveFileTransactedW CloseHandle = windll.kernel32.CloseHandle CreateTransaction = windll.ktmw32.CreateTransaction CommitTransaction = windll.ktmw32.CommitTransaction def atomic_rename_file(src, dst): transaction = CreateTransaction( None, # the handle cannot be inherited by child processes 0, 0, 0, 0, None, # no timeout None) # no description if transaction == -1: raise Exception("Unable to create a transaction") try: flags = MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH ok = MoveFileTransacted(src, dst, None, None, flags, transaction) if ok: CommitTransaction(transaction) else: raise Exception("MoveFileTransacted() error") finally: CloseHandle(transaction)