Moving all files from one folder to multiple folders and renaming them by adding suffix
Solution 1:
Since Python 3.4, working with paths is most easily done with pathlib
. Let's break it down to steps:
-
Only take files ending with
_0
. Usingglob
you can pass a pattern of the files you want to iterate over:from pathlib import Path root = Path("path/to/folder") for path in root.glob("*_0*"): ...
-
Find the matching folder to move to. That's simply taking the first two characters of the
name
:new_folder = Path("path/to/new/root", path.name[:2].upper())
Create it in case it doesn't already using
mkdir
. The argumentexist_ok
set toTrue
means it will not fail next time:new_folder.mkdir(exist_ok=True)
-
Rename the file using
with_stem
(Python >= 3.9):new_name = path.with_stem(path.stem.rpartition('_0')[0] + "_data_for_bi").name
-
Move the file to the new folder with the new name using
rename
:path.rename(new_folder / new_name)
-
All together:
from pathlib import Path root = Path("path/to/folder") for path in root.glob("*_0*"): new_folder = Path(path.name[:2].upper()) new_folder.mkdir(exist_ok=True) new_name = path.with_stem(path.stem.rpartition('_0')[0] + "_data_for_bi").name path.rename(new_folder / new_name)