Python - 如何使用 fnmatch 匹配目录

标签 python operating-system

我正在尝试使用 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 , BennyBernard但你不会看到Batman .

关于Python - 如何使用 fnmatch 匹配目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18285131/

相关文章:

Python为什么无法读取包含内容的文件?

python - 为什么在我停止程序之前不会写入文件?

linux - FreeRTOS 与 Linux 对抗单事件干扰

c - 管道上的 EOF 正在打印垃圾

memory - 字的大小和寻址

c - 有没有办法用 2 个信号量来解决生产者-消费者问题?

Clojure 中的 Python "dir"等价物

python - 如何使用 Python 查找字符串中重叠序列的数量?

python - Pytest 未从目录中选择所有测试

Python3,如何在 r.text 中找到 csrf token ?