Skip to content

file_overwrite

Atomic file overwrite via temporary file and rename.

The FileOverwrite class writes to a temporary file in the same directory as the destination, then atomically replaces the destination on context exit. This ensures that readers never see a partially-written file.

FileOverwrite

Context manager for atomic file overwrite via temp file + rename.

Writes to a temporary file in the destination directory, then replaces the destination file on exit. If an exception occurs, the destination is left untouched and the temporary file is discarded.

Example
import os
import tempfile

from py_misc_utils import file_overwrite as fow

dest = os.path.join(tempfile.gettempdir(), 'settings.json')

with fow.FileOverwrite(dest) as fd:
  fd.write('{"a": 1}')

# On exception the destination is left untouched:
try:
  with fow.FileOverwrite(dest) as fd:
    fd.write('partial')
    raise RuntimeError('boom')
except RuntimeError:
  pass

with open(dest) as fd:
  print(fd.read())  # {"a": 1}
Source code in py_misc_utils/file_overwrite.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
class FileOverwrite:
  """Context manager for atomic file overwrite via temp file + rename.

  Writes to a temporary file in the destination directory, then replaces the
  destination file on exit. If an exception occurs, the destination is left
  untouched and the temporary file is discarded.

  Example:
    import os
    import tempfile

    from py_misc_utils import file_overwrite as fow

    dest = os.path.join(tempfile.gettempdir(), 'settings.json')

    with fow.FileOverwrite(dest) as fd:
      fd.write('{"a": 1}')

    # On exception the destination is left untouched:
    try:
      with fow.FileOverwrite(dest) as fd:
        fd.write('partial')
        raise RuntimeError('boom')
    except RuntimeError:
      pass

    with open(dest) as fd:
      print(fd.read())  # {"a": 1}
  """

  def __init__(self, dest, mode='w', **kwargs):
    """Initializes a FileOverwrite context manager.

    Args:
      dest: The destination file path to write to.
      mode: The file open mode (default 'w').
      **kwargs: Additional keyword arguments forwarded to gfs.TempFile.
    """
    self._dest = dest
    self._path = gfs.path_of(dest)
    self._mode = mode
    self._kwargs = kwargs
    self._tmpfile = None

  def __enter__(self):
    """Creates the temp file and returns a writable file handle.

    Returns:
      A file-like object writable at the temp location, or ``self._dest``
      if no filesystem path is available.
    """
    if self._path is not None:
      self._tmpfile = gfs.TempFile(nspath=self._path, mode=self._mode, **self._kwargs)

      return self._tmpfile.open()
    else:
      return self._dest

  def __exit__(self, *exc):
    """Replaces the destination with the temp file contents.

    If no exception occurred, the temp file is renamed over the destination.
    The temp file handle is always closed.

    Returns:
      False (exceptions are not suppressed).
    """
    if self._tmpfile is not None:
      try:
        if exc[0] is None:
          self._tmpfile.replace(self._path)
      finally:
        self._tmpfile.close()

    return False