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")