diff atomic/writer.py @ 1:a4188f41ca35 default tip

basically the thing
author Jeff Hammel <k0scist@gmail.com>
date Fri, 02 Jan 2015 13:22:09 -0800
parents
children
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/atomic/writer.py	Fri Jan 02 13:22:09 2015 -0800
@@ -0,0 +1,33 @@
+# -*- coding: utf-8 -*-
+
+"""
+write a file atomically
+"""
+
+# imports
+import os
+import shutil
+import tempfile
+
+# module globals
+__all__ = ['ensure_dir', 'write']
+
+def ensure_dir(directory):
+    """ensure a directory exists"""
+    if os.path.exists(directory):
+        if not os.path.isdir(directory):
+            raise OSError("Not a directory: '{}'".format(directory))
+        return directory
+    os.makedirs(directory)
+    return directory
+
+
+def write(contents, path):
+    """atomically write a file taking advantage of move"""
+
+    path = os.path.abspath(path)
+    fd, tmp_path = tempfile.mkstemp()
+    os.write(fd, contents)
+    os.close(fd)
+    ensure_dir(os.path.dirname(path))
+    shutil.move(tmp_path, path)