Advertisement
DeaD_EyE

example with pathlib to move files with extensions

Mar 9th, 2023
1,068
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.11 KB | None | 0 0
  1. import shutil
  2. from pathlib import Path
  3.  
  4. # extensions = set(p.suffix for p in Path().glob("*") if p.suffix)
  5. types = {"images": ".jpg .png .svg".split(), "sound": ".m4a .mp3 .opus .wav".split()}
  6. root = Path("/mnt/vm/backup_home")
  7. for file_type, extensions in types.items():
  8.     destination = Path(root, file_type)
  9.     destination.mkdir(exist_ok=True, parents=True)
  10.     for ext in extensions:
  11.         for source_file in Path().glob(f"*{ext}"):
  12.             destination_file = destination / source_file
  13.             if destination_file.exists():
  14.                 print(f"'{source_file}' exists in target directroy. Skipping ...")
  15.                 continue
  16.  
  17.             msg = f"{{}} '{source_file}' to '{destination_file}'"
  18.  
  19.             try:
  20.                 source_file.rename(destination_file)
  21.                 print(msg.format("Renamed File"))
  22.             except OSError:
  23.                 shutil.move(source_file, destination_file)
  24.                 print(msg.format("Cross Filesystem move of"))
  25.             except Exception as e:
  26.                 print("Unexpected error, stopping")
  27.                 raise e from None
  28.  
Tags: pathlib
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement