filing.py
Language Python797 B29 lines
"""Collision-safe names and moves: never overwrite, add ' (2)', ' (3)', ..."""from __future__ import annotationsimport shutilfrom pathlib import Pathdef unique_path(directory: Path, name: str) -> Path:directory.mkdir(parents=True, exist_ok=True)target = directory / namestem, suffix = Path(name).stem, Path(name).suffixn = 2while target.exists():target = directory / f"{stem} ({n}){suffix}"n += 1return targetdef write_unique(directory: Path, name: str, text: str) -> Path:target = unique_path(directory, name)target.write_text(text, encoding="utf-8")return targetdef move_unique(src: Path, directory: Path) -> Path:target = unique_path(directory, src.name)shutil.move(str(src), str(target))return target