In Python, you can create files atomically by writing to a temporary file first and then renaming it to the final destination. This ensures that other processes either see the complete file or nothing at all. Here are the main approaches:
Using tempfile with rename
python
import tempfile
import os
def write_file_atomically(filepath, content):
# Create a temporary file in the same directory as the target
dir_name = os.path.dirname(filepath)
with tempfile.NamedTemporaryFile(mode='w', dir=dir_name, delete=False) as tmp_file:
tmp_file.write(content)
tmp_file.flush()
os.fsync(tmp_file.fileno()) # Ensure data is written to disk
temp_path = tmp_file.name
# Atomically rename the temp file to the target path
os.replace(temp_path, filepath) # os.replace is atomic on POSIX and Windows
Using context manager for cleaner code
python
import tempfile
import os
from contextlib import contextmanager
@contextmanager
def atomic_write(filepath, mode='w'):
dir_name = os.path.dirname(filepath)
with tempfile.NamedTemporaryFile(mode=mode, dir=dir_name, delete=False) as tmp_file:
try:
yield tmp_file
tmp_file.flush()
os.fsync(tmp_file.fileno())
os.replace(tmp_file.name, filepath)
except:
os.unlink(tmp_file.name) # Clean up on error
raise
# Usage
with atomic_write('/path/to/file.txt') as f:
f.write('Hello, world!')
Using the atomicwrites library
For a more robust solution, you can use the third-party atomicwrites library:
bash
pip install atomicwrites
python
from atomicwrites import atomic_write
with atomic_write('file.txt', overwrite=True) as f:
f.write('Hello, world!')
Important considerations:
Same filesystem: The temporary file must be created on the same filesystem as the target file for the rename operation to be atomic.
Platform differences: os.replace() is atomic on POSIX systems and Windows (Python 3.3+). On older Python versions, use os.rename() on POSIX systems.
Permissions: The temporary file may have different permissions than intended. You might need to set permissions explicitly:
python
import stat
def write_file_atomically_with_perms(filepath, content, mode=0o644):
dir_name = os.path.dirname(filepath)
with tempfile.NamedTemporaryFile(mode='w', dir=dir_name, delete=False) as tmp_file:
tmp_file.write(content)
tmp_file.flush()
os.fsync(tmp_file.fileno())
temp_path = tmp_file.name
# Set permissions before renaming
os.chmod(temp_path, mode)
os.replace(temp_path, filepath)
Binary files: For binary files, use mode='wb' in the temporary file creation.
The key principle is that file renames within the same filesystem are atomic operations on most modern operating systems, so readers will either see the old complete file or the new complete file, never a partially written file.