50 lines
1.0 KiB
Python
Executable File
50 lines
1.0 KiB
Python
Executable File
|
|
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, silent=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
|
|
if not silent:
|
|
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)
|
|
|