[英]Using fnmatch.fnmatch(path, “*”) - does it match everything?
[英]Python - how to match directories using fnmatch
我正在嘗試使用fnmatch來匹配Python中的目錄。 但是,不僅返回與模式匹配的目錄,還返回所有目錄或不返回任何目錄。
例如:F:\\ Downloads具有子目錄\\ The Portland Show,\\ The LA Show等
我試圖僅在\\ The Portland Show目錄中查找文件,但它還會返回LAS show等。
這是代碼:
for root, subs, files in os.walk("."):
for filename in fnmatch.filter(subs, "The Portland*"):
print root, subs, files
我得到的不僅僅是目錄的子目錄,而不僅僅是目錄“ The Portland Show”。 我究竟做錯了什么?
我只會使用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
在這種情況下,您會看到Foo
, Bar
, Benny
和Bernard
但是不會看到Batman
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.