2011-12-27 36 views
2

,並從一個驅動器複製到另一個文件還可以得到不我使用遞歸水珠找到匹配的fnmatch

def recursive_glob(treeroot, pattern): 
    results = [] 
    for base, dirs, files in os.walk(treeroot): 

     goodfiles = fnmatch.filter(files, pattern) 
     results.extend(os.path.join(base, f) for f in goodfiles) 

return results 

廠精元。但我也想要訪問與過濾器不匹配的元素。

有人可以提供一些幫助嗎?我可以在循環中構建一個正則表達式,但必須有一個更簡單的解決方案,對吧?

在此先感謝! 拉爾斯

回答

2

如果順序並不重要,使用一組:

goodfiles = fnmatch.filter(files, pattern) 
badfiles = set(files).difference(goodfiles) 
1

os.walk環內的另一個迴路也可用於:

goodfiles = [] 
badfiles = [] 
for f in files: 
    if fnmatch.fnmatch(f, pattern): 
    goodfiles.append(f) 
    else: 
    badfiles.append(f) 

注意:使用此解決方案,您必須遍歷文件列表一次。實際上,os.path.join部分可以移動到上面的循環中。

+0

很酷,謝謝!這兩種解決方案都能解決問題。再一次,非常感謝:-) – LarsVegas 2011-12-27 14:20:36