Renaming all files/folders in first children folders but not sub-children Let's say I have this folder tree:



├──FolderParent   
  ├── FolderA   
      ├── FolderAA_IMG             -- should be renamed
          ├── file_IMG_AA1.txt     -- should NOT be renamed
          ├── file_VID_AA1.txt     -- should NOT be renamed
      ├── file_IMG_A1.txt          -- should be renamed
      ├── file_PANO_A1.txt         -- should be renamed
  ├── FolderB   
      ├── file_IMG_B1.txt          -- should be renamed
      ├── file_PANO_B1.txt         -- should be renamed


As you can see, only the files/folders in the first children folder should be renamed, not the other ones. I follow this base code and then I added a second loop above but I wonder if the double for loop is the right way to go.



import os

# custom var
path= r"C:\Users\user\FolderParent"

# other cvar
number_modified_files= 0

# get all path of subfolder
all_subfolders = [f.path for f in os.scandir(path) if f.is_dir() ] 
print(all_subfolders)

for folder in all_subfolders: 
    # set the path to the folder: otherwise the rename file won't work 
    os.chdir(folder)
    #won't rename files in subfolder but will rename folder in the path 
    for filename in os.listdir(folder):
        print("new file:", filename)
        if "IMG_" in filename:
            os.rename(filename, filename.replace('IMG_', ''))
            number_modified_files +=1
        elif "PANO_" in filename:
            os.rename(filename, filename.replace('PANO_', ''))
            number_modified_files +=1
        elif "VID_" in filename:
            os.rename(filename, filename.replace('VID_', ''))   
            number_modified_files +=1


print(f"End : {number_modified_file} files renamed")
You should rethink your solution in terms of regexes:

#!/usr/bin/env python3

import re
from os import scandir, rename, path


def rename_children(parent):
    n_renamed = 0
    re_fname = re.compile('(IMG|PANO|VID)_')

    for child_dir in scandir(parent):
        if child_dir.is_dir():
            for child in scandir(child_dir):
                renamed = re_fname.sub('', child.name)
                if renamed != child.name:
                    new_path = path.join(child_dir.path, renamed)
                    print(f'Renaming {child.path} to {new_path}')
                    rename(child.path, new_path)
                    n_renamed += 1
    print(f'{n_renamed} files renamed')


Note the following changes:


Only one if to check whether the regex matches
Use scandir instead of listdir
Do not call chdir; there's no point
Don't call replace; the pattern check and the replacement operation can be combined by using sub
Don't store a list of all_subfolders; simply iterate over the results