Question

I have inherited some code that uses os.walk to traverse sections of the file system.

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?

I ran a few tests with ".", "..", ".hidden", "normal.name", "normal" and similar, but nothing seems to be filtered out.

I can't see anything in the documentation, and I'm guessing the line was added for a reason, can anyone enlighten me?

Was it helpful?

Solution

Yes, it matches everything. If you trace through the source code for fnmatch.fnmatch, it boils down to a regex match on the pattern

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. 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top