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:

  1. Only take files ending with _0. Using glob 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*"):
        ...
    
  2. 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 argument exist_ok set to True means it will not fail next time:

        new_folder.mkdir(exist_ok=True)
    
  3. Rename the file using with_stem (Python >= 3.9):

        new_name = path.with_stem(path.stem.rpartition('_0')[0] + "_data_for_bi").name
    
  4. Move the file to the new folder with the new name using rename:

        path.rename(new_folder / new_name)
    
  5. 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)