Rename subfolder in multiple folders by replacing a part of the string

Question:

Assuming I have multiple subfolders inside many different folders (**). All the folders are in a main folder called Project1. I want to replace the string name of the folders using substring function.

import glob
import os 
import pandas as pd

paths = glob.glob("CC:/Users/xxx/College/Project1/**/", recursive=True)

Assuming the subfolders are in multiple folders and have a naming convention as follows:

fwjekljfwelj-10-fwefw #(the path for this folder is "CC:/Users/xxx/College/Project1/**/wjekljfwelj-10-fwefw/")
kljkgpjrjrel-11-wwref
fwefjkecmuon-12-cfecd
dsfshncrpout-13-lplce

The alphanumeric sequence prior to the – character is meaningless. I want to replace the string preceding the dashed line with the number 20. The new subfolders would thus be:

2010-fwefw
2011-wwref
2012-cfecd
2013-lplce

I can do it individually for each subfolder using str.split('-', 1)[-1] and then append ’20’ to the name, but I would like to automate the process.
I am renaming folder names, not the files themselves.

Asked By: JodeCharger100

||

Answers:

Let’s see if this works for you:

import os
import glob

# define the base folder
base_folder = "CC:/Users/xxx/College/Project1"

# get all the subfolders
subfolders = glob.glob(os.path.join(base_folder, "**/"), recursive=True)

# iterate over the subfolders
for folder_path in subfolders:
    # get the folder name
    folder_name = os.path.basename(folder_path)
    # split the folder name by the "-" character
    parts = folder_name.split("-")
    # construct the new folder name
    new_folder_name = "20" + parts[-1]
    # get the parent folder path
    parent_folder = os.path.dirname(folder_path)
    # construct the new folder path
    new_folder_path = os.path.join(parent_folder, new_folder_name)
    # rename the folder
    os.rename(folder_path, os.path.join(parent_folder, new_folder_path))
Answered By: bit_scientist

You can use os.walk with topdown=False:

import re
import os

top_dir = 'CC:/Users/xxx/College/Project1'

for dirpath, dirnames, filenames in os.walk(top_dir, topdown=False):
    for dirname in dirnames:
        if re.search(r'-d{2}-', dirname):
            new_dirname = f"20{dirname.split('-', 1)[1]}"
            new_dirpath = os.path.join(dirpath, new_dirname)
            old_dirpath = os.path.join(dirpath, dirname)
            print(f'{old_dirpath} -> {new_dirpath}')
            os.rename(old_dirpath, new_dirpath)

Before:

Project1
└── fldr1
    ├── dsfshncrpout-13-lplce
    ├── fwefjkecmuon-12-cfecd
    ├── fwjekljfwelj-10-fwefw
    └── kljkgpjrjrel-11-wwref

After:

Project1
└── fldr1
    ├── 2010-fwefw
    ├── 2011-wwref
    ├── 2012-cfecd
    └── 2013-lplce
Answered By: Corralien
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.