2012-07-12 56 views
4

好吧,我不僅在問題本身遇到問題,而且即使試圖解釋我的問題。我有一個目錄樹由大約7次迭代,所以:rootdir/a/b/c/d/e/f/destinationdirPython Glob.glob:根和目標之間的目錄數量的通配符

的事情是有的可有5倍子目錄的水平,有些可能有多達十個,如:

rootdir/a/b/c/d/destinationdir 

或:

rootdir/a/b/c/d/e/f/g/h/destinationdir

它們唯一共同的地方是目標目錄總是被命名爲相同的東西。我使用的水珠功能的方法如下:

for path in glob.glob('/rootdir/*/*/*/*/*/*/destinationdir'):
--- os.system('cd {0}; do whatever'.format(path))

然而,這僅適用於具備中級子目錄是精確數量的目錄。有什麼辦法可以讓我不必指定那個數字subdirectories(asterices);換句話說,無論中間子目錄的數量是多少,函數都會到達destinationdir,並允許我遍歷它們。非常感謝!

回答

4

我認爲這可能與os.walk更容易做到:

def find_files(root,filename): 
    for directory,subdirs,files in os.walk(root): 
     if filename in files: 
      yield os.join(root,directory,filename) 

當然,這並不讓你在文件名部分的全局正則表達式,但你可以使用正則表達式檢查的東西或的fnmatch。

編輯

或者查找目錄:

def find_files(root,d): 
    for directory,subdirs,files in os.walk(root): 
     if d in subdirs: 
      yield os.join(root,directory,d) 
1

您可以爲縮進的每個級別(增加10如果需要的話)的模式:

for i in xrange(10): 
    pattern = '/rootdir/' + ('*/' * i) + 'destinationdir' 
    for path in glob.glob(pattern): 
     os.system('cd {0}; do whatever'.format(path)) 

這將遍歷:

'/rootdir/destinationdir' 
'/rootdir/*/destinationdir' 
'/rootdir/*/*/destinationdir' 
'/rootdir/*/*/*/destinationdir' 
'/rootdir/*/*/*/*/destinationdir' 
'/rootdir/*/*/*/*/*/destinationdir' 
'/rootdir/*/*/*/*/*/*/destinationdir' 
'/rootdir/*/*/*/*/*/*/*/destinationdir' 
'/rootdir/*/*/*/*/*/*/*/*/destinationdir' 
'/rootdir/*/*/*/*/*/*/*/*/*/destinationdir' 

如果你有遍歷任意深度的目錄那麼我建議將算法分爲兩個步驟:您調查所有'destinationdir'目錄所在的位置的一個階段,以及您執行操作的第二個階段。

1

使用更多功能的工具(如find命令(您的os.system調用表明您處於類似unix的系統,因此這將起作用))看起來更容易完成。

os.system('find /rootdir -mindepth 5 -maxdepth 10 -type d -name destinationdir | while read d; do (cd $d && do whatever;); done') 

..Note,如果你打算把所有用戶提供的字符串轉換成該命令,這種急劇變不安全的,你應該使用subprocess.Popen代替,執行外殼和分裂自己的論點。儘管如此,它是安全的。

2

如果您正在尋找的文件,你可以使用Formic package(披露:我寫的) - 這個實現的Apache Ant的文件集水珠與'**'通配符:

import formic 
fileset = formic.FileSet(include="rootdir/**/destinationdir/*") 

for file_name in fileset: 
    # Do something with file_name