简体   繁体   English

更改 Python 中的文件夹名称

[英]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 ):我在My Music文件夹中,我想更改所有子文件夹的名称( This_Is_A_Example_Subpath ):

C:/My Music/This_Is_A_Example_- Subpath C:/我的音乐/This_Is_A_Example_- 子路径
C:/My Music/This_Is_A_Example_- Subpath1 C:/我的音乐/This_Is_A_Example_- Subpath1
C:/My Music/This_Is_A_Example_- Subpath2 C:/我的音乐/This_Is_A_Example_- Subpath2

I want to change to:我想更改为:

C:/My Music/This Is - A Example - Subpath C:/My Music/This Is - 示例 - 子路径
C:/My Music/This Is - A Example - Subpath1 C:/我的音乐/这是 - 示例 - 子路径 1
C:/My Music/This Is - A Example - Subpath2 C:/我的音乐/这是 - 示例 - 子路径 2

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 .这使用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.所以这(1)重命名目录,(2)更新列表,以便它遍历新命名的目录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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