Crash-Safe File Update

Hard ⏱ 18 min 38% acceptance ★★★★★ 4.8
If a program crashes mid-write, a config file can be left half-written. Write safe_save(path, text) that writes text to a temporary file path + '.tmp' first and only then atomically renames it over the original with os.replace — the standard write-temp-then-swap pattern.

Examples

Example 1
Input
safe_save('settings.ini', 'mode=dark')
Output
settings.ini now holds mode=dark, never a partial write
Explanation

The rename is atomic; readers see either the old or the new file, never a torn one.

Constraints

  • Write to path + ".tmp" first.
  • Finish with os.replace(tmp, path).

Topics

File Handlingatomic write

Companies

GoogleStripePayPal

Hints

Hint 1

Close the temp file before renaming (leave the with block).

Hint 2

os.replace works even when the target exists.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.