简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM