0

Is there a way to check if a directory is in the path of a python Path object. I know I can test it by converting it to a string like 'dir' in str(Path('/dir/dir2/dir3')) or 'dir' in Path('/dir/dir2/dir3').parts but I'm hoping there is a built in method. I've checked the documentation but didn't see anything that is a builtin method that would do this.

Matthew Barlowe
  • 2,229
  • 1
  • 14
  • 24

1 Answers1

1
from pathlib import Path
p=Path('/dir/dir2/dir3')
if p.match("*dir*"):
    print("found 'dir' in path")

This should find if dir is anywhere in the given path.

Tyberius
  • 625
  • 2
  • 12
  • 20
  • Was hoping wouldn't have to use globs but this does answer the question of using a built in method so accepted – Matthew Barlowe Jun 20 '21 at 21:41
  • 1
    @MatthewBarlowe I think without globs, your best bet is still your 2nd option of splitting the path with `parts` and seeing if `dir` is in that tuple. – Tyberius Jun 20 '21 at 21:58