Atomic File Writes

1.4.1 · deprecated · verified Thu Apr 09

Atomicwrites is a Python library that provides a simple, high-level API for performing atomic file writes. It achieves atomicity by writing to a temporary file in the same directory and then atomically moving it to the target location. This prevents file corruption in case of crashes or interruptions during the write process. The library is currently at version 1.4.1. While previously actively maintained, its status has shifted due to the maintainer's decision regarding PyPI 2FA requirements, leading to its deprecation. Users are encouraged to consider alternatives like `safer` for new projects.

Warnings

Install

Imports

Quickstart

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}")

view raw JSON →