Reference library

Files & data

Read and write files safely; parse JSON, CSV, and common text formats.

2 matches
Files & data medium

How to Atomically Write Files in Python with Temp File and Rename

Write a file atomically using a temporary file and os.replace so readers never see partial writes even if the process crashes mid-write.

atomic-write tempfile fsync
Python
import os
import tempfile
from pathlib import Path

def atomic_write(path: str | Path, content: str) -> None:
    """Write content to path atomically using a temp file and rename."""
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)

    fd, temp_path = tempfile.mkstemp(
        dir=str(path.par…
17 0 Open
Files & data medium

How to Write a List of Lines to a Text File Safely in Python

This code atomically writes a list of strings as lines to a text file using a temporary file and os.replace to prevent corruption.

files atomic-write pathlib
Python
from pathlib import Path
import tempfile
import os

def write_lines_safely(lines: list[str], filepath: str | Path) -> None:
    """Write lines to a text file atomically to avoid corruption."""
    path = Path(filepath)
    path.parent.mkdir(parents=True, exist_ok=True)
    
    fd, temp_path = tempfile.mkstemp(dir=str…
13 0 Open

Browse by section

Each section groups closely related Python snippets.

Files & data — Python code examples

What you will find here

This page collects files & data snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.