import shutil from pathlib import Path # extensions = set(p.suffix for p in Path().glob("*") if p.suffix) types = {"images": ".jpg .png .svg".split(), "sound": ".m4a .mp3 .opus .wav".split()} root = Path("/mnt/vm/backup_home") for file_type, extensions in types.items(): destination = Path(root, file_type) destination.mkdir(exist_ok=True, parents=True) for ext in extensions: for source_file in Path().glob(f"*{ext}"): destination_file = destination / source_file if destination_file.exists(): print(f"'{source_file}' exists in target directroy. Skipping ...") continue msg = f"{{}} '{source_file}' to '{destination_file}'" try: source_file.rename(destination_file) print(msg.format("Renamed File")) except OSError: shutil.move(source_file, destination_file) print(msg.format("Cross Filesystem move of")) except Exception as e: print("Unexpected error, stopping") raise e from None