Files
2026-04-14 23:53:03 +02:00

50 lines
995 B
Python

from pathlib import Path
import shutil
# -----------------------------
# Helpers
# -----------------------------
def safe_delete(path: Path):
if path.is_dir():
shutil.rmtree(path)
else:
path.unlink()
def safe_rename(src: Path, dst: Path, dry: bool=False, confirm: bool=False):
"""
Safely rename a file or directory without overwriting existing files.
Automatically appends _1, _2, ... if needed.
"""
src = Path(src)
dst = Path(dst)
# nothing to do
if src.resolve() == dst.resolve():
return
directory = dst.parent
base = dst.stem
ext = dst.suffix
final_dst = dst
counter = 1
# find free name
while final_dst.exists():
final_dst = directory / f"{base}_{counter}{ext}"
counter += 1
print(f"{src} → {dst}")
if dry:
return
if confirm:
input("Press Enter to confirm...")
dst.parent.mkdir(parents=True, exist_ok=True)
src.rename(dst)