I have a folder with many sub-folders, and each sub-folder also has two sub-folders. The structure looks like this:
--folder --sub-f1 --1-1000 --1-1050 --sub-f2 --1-1030 --1-1060 --sub-f3 --1-1040 --1-1070
What I want to achieve is extract the folder with smaller number in name(in the above example, 1-1000, 1-1030 and 1-1040) and rename these folders according to their parent folders(sub-f1-1, sub-f2-1 and sub-f3-1). I’m running Windows 10 and any simple solutions are welcome!
Advertisement
Answer
I have written a fairly verbose algorithm to explain step by step how it works:
from glob import glob import os root_dir = 'folder' # specify here your root dir, in your example is "folder" parent_dirs = glob(f"{root_dir}/*", recursive=True) # detect all first level subdirs for parent in parent_dirs: # for each parent dirs, detect all childs child_dirs = glob(f"{parent}/*", recursive=True) # for each child, extract the last part of name (e.g. 1000) and append to list child_nums = [] for child in child_dirs: child_nums.append(child.split(os.sep)[-1].split("-")[-1]) # find smallest child num and its index in list to retrieve corrispondent full path small_child = min(child_nums) small_child_index = child_nums.index(small_child) src_folder = child_dirs[small_child_index] # compose the destination dir name dst_folder = os.path.join(parent, parent.split(os.sep)[1] + "-1") os.rename(src_folder, dst_folder) print(f"src_folder '{src_folder}' renamed as: '{dst_folder}'")
output will be:
src_folder 'foldersub-f11-1000' renamed as: 'foldersub-f1sub-f1-1' src_folder 'foldersub-f21-1030' renamed as: 'foldersub-f2sub-f2-1' src_folder 'foldersub-f31-1040' renamed as: 'foldersub-f3sub-f3-1'
This solution can be implemented in many other ways, even without using glob and just using os.walk()
for example. You can use much more optimized algorithms but it depends on how many folders you need to rename. This is just a simple example.