39 lines
1.2 KiB
Python
39 lines
1.2 KiB
Python
from pathlib import Path
|
|
import os
|
|
import sys
|
|
from typing import Callable
|
|
|
|
def for_each_file(path: Path, extensions: list[str] | None, func: Callable):
|
|
for eachFile in get_files_recursive(path, extensions):
|
|
func(eachFile)
|
|
|
|
def get_files_recursive(path: Path, extensions: list[str] | None) -> list[Path]:
|
|
if not extensions:
|
|
return list(path.rglob("*.*"))
|
|
else:
|
|
paths_list = [list(path.rglob(f"*.{ext}")) for ext in extensions]
|
|
return [p for paths in paths_list for p in paths]
|
|
|
|
def get_empty_dirs(path: Path) -> list[Path]:
|
|
return [curdir
|
|
for curdir, subdirs, files in os.walk(path)
|
|
if len(subdirs)==0 and len(files) == 0]
|
|
|
|
def _delete_empty_dirs(path: Path) -> bool:
|
|
empty_dirs = get_empty_dirs(path)
|
|
map(os.rmdir, empty_dirs)
|
|
return bool(empty_dirs)
|
|
|
|
def delete_empty_dirs_recursive(path: Path):
|
|
found_empty = True
|
|
while found_empty:
|
|
found_empty = _delete_empty_dirs(path)
|
|
|
|
def replace_filename(path: Path, replacement: str) -> Path:
|
|
return path.parent / (replacement + path.suffix)
|
|
|
|
def move_file_new_name(src: Path, dst: Path, name: str):
|
|
os.makedirs(dst, exist_ok=True)
|
|
shutil.move(src, dst / f"{name}{src.suffix}")
|
|
|
|
|