简体   繁体   English

如何在脚本python3中递归重命名子目录和文件名?

[英]How to rename sub directory and file names recursively in script python3?

I have a recursive directory. 我有一个递归目录。 Both subdirectory and files names have illegal characters. 子目录和文件名都有非法字符。 I have a function to clean up the names, such as it replaces a space with an underscore in the name. 我有一个清理名称的功能,例如它用名称中的下划线替换空格。 There must be an easier way but I couldn't find a way to both rename folders and files. 必须有一个更简单的方法,但我找不到重命名文件夹和文件的方法。 So, I want to rename the folders first. 所以,我想先重命名文件夹。

for path, subdirs, files in os.walk(root):
        for name in subdirs:     
            new_name=clean_names(name)
            name=os.path.join(path,name)
            new_name=os.path.join(path,new_name) 
            os.chdir(path)
            os.rename(name,new_name)

When I check my real folder and it contents I see that only the first subfolder name is corrected. 当我检查我的真实文件夹及其内容时,我看到只有第一个子文件夹名称被更正。 I can see the reason because os.chdir(path) changes the cwd then it doesn't change back before for loop starts to second path. 我可以看到原因,因为os.chdir(path)改变了cwd然后它没有改变回来之前循环开始到第二个路径。 I thought after the os.rename I could rechange the cwd but I am sure there is a more elegant way to do this. 我想在os.rename后我可以改变cwd,但我相信有更优雅的方式来做到这一点。 If I remove the os.chdir line it gives filenotfound error. 如果我删除os.chdir行,它会给出filenotfound错误。

I see that renaming subdirectories has been asked about before, but they are in command line. 我看到之前已经询问过重命名子目录,但是它们在命令行中。

You should use os.walk(root, topdown=False) instead; 你应该使用os.walk(root, topdown=False) ; otherwise once the top folder gets renamed, os.walk won't have access to the subfolders because it can no longer find their parent folders. 否则,一旦顶层文件夹被重命名, os.walk将无法访问子文件夹,因为它无法再找到其父文件夹。

Excerpt from the documentation : 摘自文档

If optional argument topdown is True or not specified, the triple for a directory is generated before the triples for any of its subdirectories (directories are generated top-down). 如果可选参数topdownTrue或未指定,则在其任何子目录的三元组(目录从上向下生成)之前生成目录的三元组。 If topdown is False , the triple for a directory is generated after the triples for all of its subdirectories (directories are generated bottom-up). 如果topdownFalse ,则在所有子目录的三元组(自下而上生成目录)之后生成目录的三元组。 No matter the value of topdown, the list of subdirectories is retrieved before the tuples for the directory and its subdirectories are generated. 无论topdown的值如何,都会在生成目录及其子目录的元组之前检索子目录列表。

Note that you do not need to call os.chdir at all because all the paths passed to os.rename are absolute. 请注意,您根本不需要调用os.chdir ,因为传递给os.rename所有路径都是绝对路径。

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

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