简体   繁体   English

使用fnmatch.fnmatch(path,“*”) - 它是否匹配所有内容?

[英]Using fnmatch.fnmatch(path, “*”) - does it match everything?

I have inherited some code that uses os.walk to traverse sections of the file system. 我继承了一些使用os.walk遍历文件系统部分的代码。

for (dirpath, _, filenames) in os.walk(blahblah):
    reldir = dirpath[len(base)+1:]
    if fnmatch(reldir, './lost+found'):
        continue

    for path in filenames:
        if fnmatch.fnmatch(path, "*"):
            ...

I am at a loss to understand the point of using fnmatch to match against "*", is there something that this will not match? 我无法理解使用fnmatch与“*”匹配的问题,是否存在不匹配的内容?

I ran a few tests with ".", "..", ".hidden", "normal.name", "normal" and similar, but nothing seems to be filtered out. 我用".", "..", ".hidden", "normal.name", "normal"等进行了一些测试,但似乎没有任何过滤掉。

I can't see anything in the documentation, and I'm guessing the line was added for a reason, can anyone enlighten me? 我在文档中看不到任何内容,我猜这条线是有原因的,有人可以启发我吗?

Yes, it matches everything. 是的,它符合一切。 If you trace through the source code for fnmatch.fnmatch , it boils down to a regex match on the pattern 如果你追踪fnmatch.fnmatch的源代码,它归结为模式的正则表达式匹配

In [4]: fnmatch.translate('*')
Out[4]: '.*\\Z(?ms)'

That matches 0-or-more characters followed by the end-of-string ( \\Z ), with the MULTILINE and DOTALL flags on. 匹配0或更多字符后跟字符串结尾( \\Z ),并打开MULTILINE和DOTALL标志。 That will match any string. 这将匹配任何字符串。


Maybe at some point the line 也许在某些时候这条线

if fnmatch.fnmatch(path, "*"):

used a more complicated pattern, but was later changed to "*" instead of omitting the check. 使用了更复杂的模式,但后来改为"*"而不是省略检查。 But that's just speculation. 但那只是猜测。

In any case, the if-condition could be removed, since it is always True. 在任何情况下,可以删除if-condition ,因为它始终为True。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM