2013-08-17 163 views
1

我想使用fnmatch來匹配Python中的目錄。但不是隻返回與模式匹配的目錄,而是返回所有目錄或不返回。Python - 如何使用fnmatch匹配目錄

例如: F:\下載有子目錄\波特蘭展,\洛杉磯表演等等

我試圖找到只有\波特蘭顯示目錄中的文件,但它也返回LAS秀等

下面的代碼:

for root, subs, files in os.walk("."): 
    for filename in fnmatch.filter(subs, "The Portland*"): 
    print root, subs, files 

而不是剛開子目錄「波特蘭秀」,我得到的一切目錄。我究竟做錯了什麼?

回答

2

我只想用glob

import glob 
print "glob", glob.glob('./The Portland*/*') 

有一些技巧可以但如果你真的想用os.walk由於某種原因或其他...例如,讓我們假設播放的頂級目錄只包含更多的目錄。然後你就可以確保你只能通過就地修改subs列表遞歸到正確的:

for root,subs,files in os.walk('.'): 
    subs[:] = fnmatch.filter(subs,'The Portland*') 
    for filename in files: 
     print filename 

現在,在這種情況下,你只會遞歸到與The Portland開始,那麼你將打印所有的目錄在那裏的文件名。

. 
+ The Portland Show 
| Foo 
| Bar 
+ The Portland Actors 
|  Benny 
|  Bernard 
+ Other Actors 
|  George 
+ The LA Show 
| Batman 

在這種情況下,你會看到FooBarBennyBernard,但你不會看到Batman

+0

謝謝,glob工作。非常感激! – Tensigh