Python: How to check if path is a subpath

directory, python, python-2.7

Solution

try this: `file_path.startswith(os.path.abspath(dir_path)+os.sep)`

also you can check on this: How to check whether a directory is a sub directory of another directory

so for your example:

>>> '/tmp/abc/d/my_file.py'.startswith(os.path.abspath('/tmp/abc')+os.sep)
True
>>> '/tmp/abc/d/my_file.py'.startswith(os.path.abspath('/tmp/a')+os.sep)
False

Problem

Lets say I have these paths: ``` /tmp/a /tmp/abc /tmp/abc/d/my_file.py ``` How could I check if `/tmp/abc/d/my_file.py` is a subpath of `/tmp/abc`? I tried: ``` file_path.startswith(dir_path) ``` But it returns `True` for `/tmp/a` directory, while `my_file.py` is not in it.

Original source

Related problems