Peter
Peter

Reputation: 117

Changing folder name in Python

I need a super simple script that changes the names of the subfolders of the actual folder

Here's a little example for better understanding.
Im in the folder My Music and I want to change tha name of all the subfolders (This_Is_A_Example_Subpath):

C:/My Music/This_Is_A_Example_- Subpath
C:/My Music/This_Is_A_Example_- Subpath1
C:/My Music/This_Is_A_Example_- Subpath2

I want to change to:

C:/My Music/This Is - A Example - Subpath
C:/My Music/This Is - A Example - Subpath1
C:/My Music/This Is - A Example - Subpath2

Upvotes: 2

Views: 4837

Answers (1)

Chris Eberle
Chris Eberle

Reputation: 48795

import os
import os.path

for (dirpath, dirnames, filenames) in os.walk('C:/My Music/'):
    for idx in range(len(dirnames)):
        newname = dirnames[idx].replace('_', ' ')
        os.rename(os.path.join(dirpath, dirnames[idx]), os.path.join(dirpath, newname))
        dirnames[idx] = newname

A bit of an explanation here. This walks through all of the subdirectories using os.walk. However since you're changing the name of the directory as you're traversing the tree, you need to update the directory names that it's going to walk. So this (1) renames the directory, and (2) updates the list so that it walks the newly-named directories.

Upvotes: 7

Related Questions