4

pathlib match(pattern) is documented as matching a path against a provided glob-style pattern but it doesn't work

>>> Path("w/x/y/z").mkdir(parents=True)
>>> list(Path().glob("w/**/z"))
[PosixPath('w/x/y/z')]
>>> Path("w/x/y/z").match("w/**/z")
False

Shouldn't that return true?

no step on snek
  • 324
  • 1
  • 15
  • 1
    I looked in pathlib.py (Python 3.7 -- look in lib), and aside from splitting the pattern by separator, it does no separate processing for `**`. `glob()` is typically used to search directory paths which yield multiple matches, but `match()` is used to compare specific cases. Does Path("w/x/y/z").match("w/*/*/z") work? – Ben Y Jun 03 '21 at 19:35
  • @BenY Ya, that works. `rglob()` does what he wants – myz540 Jun 04 '21 at 23:26
  • To plainly state my point, as it appears to have been lost, is that `match()` does not work the same as `glob()` or `rglob()`. It's not implemented to treat `**` as a special match for multiple levels of directories. The answer is No, as @myz540 states. – Ben Y Jun 05 '21 at 06:07

1 Answers1

0

The glob pattern of ** does not go through path delimiters. At least the path.match() function does not have it implemented. Maybe try path.rglob() which does recursive globbing.

Try:

In [1]: from pathlib import Path

In [2]: p = Path("w/z/y/z")

In [3]: p.mkdir(parents=True)

In [5]: p.match("w/*/*/z")
Out[5]: True
myz540
  • 537
  • 4
  • 7
  • I already mentioned that you can use `rglob`. Not acceptable for what? Your question does not propose a use-case. You asked if `match()` should return `True` given the glob-style pattern and the answer is no. – myz540 Jun 05 '21 at 00:04
  • 2
    `Path.match` is for checking a _string_ against a pattern. `Path.rglob` is for finding files on a filesystem which match a pattern. Those are totally different things, for using match you might not even have a filesystem available at all e.g. processing paths taken from a csv file or database. – no step on snek Jun 18 '21 at 00:44
  • 3
    So why do you think `Path("w/x/y/z").match("w/**/z")` shouldn't return True? It matches the glob pattern, doesn't it? – no step on snek Jun 18 '21 at 00:56
  • This also returns true: `Path("w/x/y/z").match("z")`, so I don't think it has anything to do with the asterisks - however, I'd expect it to require this to evaluate to true: `Path("w/x/y/z").match("**/z")`. – Jeppe Oct 02 '22 at 08:22