Coverage for little_loops / file_utils.py: 31%

16 statements  

« prev     ^ index     » next       coverage.py v7.12.0, created at 2026-05-11 00:29 -0500

1"""Shared file I/O utilities for little-loops.""" 

2 

3from __future__ import annotations 

4 

5import os 

6import tempfile 

7from pathlib import Path 

8 

9 

10def atomic_write(path: Path, content: str, encoding: str = "utf-8") -> None: 

11 """Write *content* to *path* atomically using tempfile + os.replace. 

12 

13 Writes to a sibling temp file in the same directory (same filesystem), 

14 then renames it over the target so readers never observe a partial file. 

15 """ 

16 tmp_fd, tmp_path = tempfile.mkstemp(dir=path.parent, suffix=".tmp") 

17 try: 

18 with os.fdopen(tmp_fd, "w", encoding=encoding) as f: 

19 f.write(content) 

20 os.replace(tmp_path, path) 

21 except Exception: 

22 try: 

23 os.unlink(tmp_path) 

24 except FileNotFoundError: 

25 pass 

26 raise