2016-11-11 128 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 –