【问题标题】:Get also elements that don't match fnmatch获取与 fnmatch 不匹配的元素
【发布时间】:2023-04-07 22:22:02
【问题描述】:

我正在使用递归 glob 来查找文件并将其从驱动器复制到另一个驱动器

def recursive_glob(treeroot, pattern):
   results = []
   for base, dirs, files in os.walk(treeroot):

      goodfiles = fnmatch.filter(files, pattern)
      results.extend(os.path.join(base, f) for f in goodfiles)

return results

工作正常。但我也想访问与过滤器不匹配的元素。

有人可以提供帮助吗?我可以在循环中构建一个正则表达式,但必须有一个更简单的解决方案,对吧?

【问题讨论】:

    标签: python glob recursive-datastructures fnmatch


    【解决方案1】:

    如果顺序无关紧要,请使用集合:

    goodfiles = fnmatch.filter(files, pattern)
    badfiles = set(files).difference(goodfiles)
    

    【讨论】:

      【解决方案2】:

      os.walk 循环内的另一个循环也可以使用:

      goodfiles = []
      badfiles = []
      for f in files:
        if fnmatch.fnmatch(f, pattern):
          goodfiles.append(f)
        else:
          badfiles.append(f)
      

      注意:使用此解决方案,您只需遍历文件列表一次。其实os.path.join部分可以移到上面的循环中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-26
        • 1970-01-01
        • 2012-05-30
        • 2016-06-02
        • 1970-01-01
        • 2018-06-03
        • 1970-01-01
        • 2016-05-27
        相关资源
        最近更新 更多