Skip to content

Instantly share code, notes, and snippets.

Last active September 25, 2015 08:29
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Cross-platform nearly ACID file updates
import platform
import tempfile
import ntpath
import filelock #
# It's interesting to see what's different between Windows and Linux.
# On Windows, you can't rename to an existing file, and you can't
# use os.fdatasync().
# Also see:
def write_file(full_pathname, data):
with filelock.FileLock(full_pathname):
with tempfile.NamedTemporaryFile(mode='w',
delete=False) as f:
write_data_to_file(f, data)
# exiting this "with" flushes, but does not sync
if platform.system() == "Windows":
os.fsync(f.fileno()) # Slower, but cross-platform
if os.path.exists(full_pathname):
os.unlink(full_pathname) # otherwise WindowsError
os.fdatasync(f.fileno()) # Faster, Unix only
tempname =
os.rename(tempname, full_pathname) # Atomic on Unix, not Windows
except filelock.FileLockException as e:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment