我有一个递归目录.子目录和文件名均包含非法字符.我有一个清理名称的功能,例如它用名称中的下划线替换了空格.必须有一种更简单的方法,但我找不到重命名文件夹和文件的方法.因此,我想先重命名文件夹.
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)
当我检查我的真实文件夹及其内容时,我看到只有第一个子文件夹名称被更正.我可以看到原因,因为os.chdir(path)更改了cwd,然后在for循环开始到第二条路径之前它没有更改.我以为在os.rename之后我可以更改cwd,但是我敢肯定有更优雅的方法可以做到这一点.如果我删除os.chdir行,则会出现filenotfound错误.
我看到以前曾有人问过重命名子目录,但是它们在命令行中.
documentation的节选:
If optional argument
topdown
isTrue
or not specified,the triple for
a directory is generated before the triples for any of its
subdirectories (directories are generated top-down). Iftopdown
is
False
,the triple for a directory is generated after the triples for
all of its subdirectories (directories are generated bottom-up). No
matter the value of topdown,the list of subdirectories is retrieved
before the tuples for the directory and its subdirectories are
generated.