【问题标题】:Python - how to match directories using fnmatchPython - 如何使用 fnmatch 匹配目录
【发布时间】:2013-08-17 04:31:59
【问题描述】:

我正在尝试使用 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”,而是获取目录中的所有内容。我做错了什么?

【问题讨论】:

    标签: python operating-system


    【解决方案1】:

    我只会使用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

    【讨论】:

      猜你喜欢
      • 2023-04-07
      • 1970-01-01
      • 2016-01-05
      • 1970-01-01
      • 1970-01-01
      • 2015-02-25
      • 1970-01-01
      • 2019-03-27
      • 2010-11-08
      相关资源
      最近更新 更多