DeaD_EyE icon

example with pathlib to move files with extensions

DeaD_EyE | PRO | 03/09/23 11:30:13 PM UTC | 0 ⭐ | 1546 👁️ | Never ⏰ | [pathlib]
Python |

1.11 KB

|

None

|

0 👍

/

0 👎

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
 

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎