我正在尝试使用 fnmatch 来匹配 Python 中的目录。但它不是只返回与模式匹配的目录,而是返回所有目录或不返回任何目录。
例如: F:\Downloads 有子目录\The Portland Show、\The LA Show 等
我试图仅在\The Portland Show 目录中查找文件,但它也会返回 The 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
.
关于Python - 如何使用 fnmatch 匹配目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18285131/