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 | |