Install & Compatibility
Where this runs
tested against v1.4.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.95 runs
installs and imports cleanly · install 0.0s · import 0.014s · 19.2MB
glibcpy 3.10–3.95 runs
installs and imports cleanly · install 2.5s · import 0.014s · 20MB
17MB installed
● package 17MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
atomic_write
✓ from atomicwrites import atomic_write
The primary high-level context manager for atomic file operations.
AtomicWriter
✓ from atomicwrites import AtomicWriter
A lower-level, class-based API for more granular control over atomic writes.
This example demonstrates how to use `atomic_write` to safely write JSON data to a file. The `overwrite=True` parameter allows replacing an existing file. If an error occurs during the write, the original file remains untouched. The example also includes cleanup for re-runnability and demonstrates reading the content back.
import os
from atomicwrites import atomic_write
import json
file_path = "my_config.json"
config_data = {"api_key": os.environ.get('MY_API_KEY', 'default_secret'), "timeout": 30}
try:
# Write configuration atomically
with atomic_write(file_path, overwrite=True, encoding='utf-8') as f:
json.dump(config_data, f, indent=2)
print(f"Configuration successfully written to {file_path}")
# Verify content by reading back
with open(file_path, 'r', encoding='utf-8') as f:
read_config = json.load(f)
print(f"Read back configuration: {read_config}")
except Exception as e:
print(f"An error occurred during atomic write: {e}")
# In case of an error, the original file (if any) should be intact
# or no partial file should exist if it was a new creation.
if not os.path.exists(file_path):
print(f"Target file {file_path} does not exist after error (expected behavior for new file).")
else:
print(f"Target file {file_path} exists after error (expected behavior if original was preserved).")
finally:
# Clean up the created file for a runnable example
if os.path.exists(file_path):
os.remove(file_path)
print(f"Cleaned up {file_path}")
Debug
Known issues
deprecatedThe `atomicwrites` library is officially deprecated by its maintainer as of July 2022. The maintainer indicated that Python 3's built-in `os.replace` and `os.rename` functions might suffice for many use cases, and cited PyPI's 2FA requirements as a reason for deprecation.fixFor new projects, consider actively maintained alternatives like `safer`. For simple atomic renames, Python's `os.replace` (for overwriting) or a combination of `tempfile` and `os.rename` can be used.
affects: 1.4.1 and later (effectively all versions due to maintainer's stance)
gotchaOn Windows, the atomicity of the `MoveFileEx` system call (used by `atomicwrites`) is not universally guaranteed. It can, under certain conditions, silently fall back to a non-atomic copy-and-delete operation, potentially leading to data inconsistencies if the system crashes during this fallback.fixBe aware of this platform-specific limitation. For critical applications on Windows requiring absolute atomicity, additional verification or platform-specific mechanisms might be necessary. Thorough testing on the target Windows environment is recommended.
affects: All versions
gotchaAtomic file operations are only guaranteed if the temporary file created by `atomicwrites` and the final target file reside on the *same filesystem*. If they are on different filesystems (e.g., a network drive vs. local disk), the operation might fall back to a non-atomic copy, which is susceptible to interruption failures.fixEnsure that the target file path is on the same filesystem as the directory where temporary files will be created (by default, `atomicwrites` creates temporary files in the same directory as the target path to mitigate this).
affects: All versions
gotchaWhen `overwrite=False` is used in `atomic_write` (which employs `os.link` and `os.unlink` on POSIX systems), there is a brief time window where the file might be accessible under both its temporary name and the target name. Additionally, this method may lead to changes in the target file's permissions if the link operation doesn't preserve them as expected.fixIf `overwrite=False` is critical, carefully test and verify permission preservation on your target platform. Design applications to be robust against a brief dual-presence of the file.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'atomicwrites'
The 'atomicwrites' package is not installed in the Python environment.
fixInstall the package using 'pip install atomicwrites'.
ImportError: cannot import name 'atomic_write' from 'atomicwrites'
The function 'atomic_write' is not available in the 'atomicwrites' module.
fixEnsure you are using the correct function or class from the 'atomicwrites' module.
AttributeError: module 'atomicwrites' has no attribute 'atomic_write'
The 'atomic_write' function is not defined in the 'atomicwrites' module.
fixVerify the module's documentation for the correct usage and available functions.
FileExistsError: [Errno 17] File exists: 'your_file_name.txt'
You are attempting to write to a file using `atomic_write` with `overwrite=False` (the default for some modes) and the target file already exists.
fixExplicitly set `overwrite=True` in your `atomic_write` call if you intend to replace the existing file: `with atomic_write('your_file_name.txt', overwrite=True) as f:` ValueError: invalid mode: 'a'
The `atomic_write` function or `AtomicWriter` class does not support append ('a') or other non-write modes, as atomic appends are inherently complex and not directly supported by the library's core mechanism (rename/replace).
fixRead the file content, modify it in memory, and then use `atomic_write` with a write mode ('w' or 'wb') to atomically replace the entire file. `atomicwrites` is designed for atomic replacement, not atomic appending. Upgrade
Version history
1.4.1latest on PyPI · released Jul 8, 2022
Audit
Dependencies
No dependency data recorded yet.