← All Exercises
Atomic File Replacement with Rollback
advancedpython
Background
A direct write can leave a truncated file after a crash; writing a sibling temp file and renaming it makes readers see either the old or the new content.
Problem
Implement atomic_write(path, data) that creates a temporary file in the destination directory, writes UTF-8 text, flushes and fsyncs it, then replaces the target with os.replace. On any exception, remove the temporary file and re-raise. Return the number of UTF-8 bytes written.
Input
A destination path and a text payload.
Output
The number of UTF-8 bytes written; the destination contains exactly the payload and no temporary files remain.
Sample tests
Sample 1
Input: path = 'out.txt', data = 'hello'
Expected: 5
Sample 2
Input: path = 'out.txt', data = 'café'
Expected: 5
Your solution
Learning objective
Implement crash-safe file replacement with a same-directory temp file and exception-safe cleanup.