2016-11-11 164 views
1

我有一个目录是这样的:重命名目录的递归在Python

enter image description here

我遇到的问题是,当使用该功能:

from os import walk 
generic_name = "{project_name}" 

def rename_project(src): 
    project_name = raw_input("Name your project: ") 
    for subdir, dirs, files in walk(src): 
     rename(subdir, subdir.replace(generic_name, project_name)) 

在到达第二个文件夹,即{project_name} Planning的整个目录已被更改。即成为:

enter image description here

,因此它出现在for ... in walk(src):停止运行。请注意,循环工作正常;我可以打印每个目录和取得的成果:

for subdir, dirs, files in walk(src): 
    print subdir 

产量...

enter image description here

用我有限的Python的知识,我认为,由于目录已经改变,这会导致异常到walk(src)并且意味着循环被终止。

我该如何解决这个问题,递归循环遍历目录并重命名所有包含{project_name}的目录?

很多感谢:)

回答

1

甲醚检查走法的自上而下的参数迭代的方法或使用递归递归遍历目录树。

编辑:好吧,我不知道一个优雅的解决方案,重命名字符串的最后发生,但在这里你去。 ;)

import os 
generic_name = "{project_name}" 

subdirs = [] 

def rename_project(src): 
    project_name = raw_input("Name your project: ") 
    for subdir, dirs, files in os.walk(src,topdown=False): 
     subdirs.append(subdir) 

    for subdir in subdirs: 
     newdir = subdir[::-1].replace(generic_name[::-1], project_name[::-1], 1)[::-1] 
     print newdir 
     #os.rename(subdir,newdir) 

rename_project(".") 

我分开收集字母并重命名(或打印^^)它们。但是你可以看到(如果你运行它)它从最内层文件夹开始递归地重命名(打印)。

我偷了马克·拜尔斯在这里的“替换 - 最后出现在字符串”rreplace - How to replace the last occurrence of an expression in a string?。 ^^

而且更干净,无例外,也许难以调试奖金版本:

import os 
generic_name = "{project_name}" 

def rename_project(src): 
    project_name = raw_input("Name your project: ") 
    for subdir, dirs, files in os.walk(src,topdown=False): 
     newdir = subdir[::-1].replace(generic_name[::-1], project_name[::-1], 1)[::-1] 
     print newdir 
     if newdir != '.': 
      os.rename(subdir,newdir) 

rename_project(".") 
+0

Settting'自上而下= TRUE;没有工作。你会如何建议我使用递归来遍历目录? – discipline

+0

嗯即时通讯只是在自上而下=假的方法,只是一秒;) –

+0

@discipline OK done。它会抛出“OSError:[Errno 16] Device or resource busy”,如果您重命名“。”。至 ”。”但它完全有效^^ - d –