![](/img/trans.png)
[英]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.