comparison 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
comparison
equal deleted inserted replaced
0:dc90512b9c98 1:a4188f41ca35
1 # -*- coding: utf-8 -*-
2
3 """
4 write a file atomically
5 """
6
7 # imports
8 import os
9 import shutil
10 import tempfile
11
12 # module globals
13 __all__ = ['ensure_dir', 'write']
14
15 def ensure_dir(directory):
16 """ensure a directory exists"""
17 if os.path.exists(directory):
18 if not os.path.isdir(directory):
19 raise OSError("Not a directory: '{}'".format(directory))
20 return directory
21 os.makedirs(directory)
22 return directory
23
24
25 def write(contents, path):
26 """atomically write a file taking advantage of move"""
27
28 path = os.path.abspath(path)
29 fd, tmp_path = tempfile.mkstemp()
30 os.write(fd, contents)
31 os.close(fd)
32 ensure_dir(os.path.dirname(path))
33 shutil.move(tmp_path, path)