Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to check if path is a subpath [duplicate]

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.

like image 657
niekas Avatar asked Jan 28 '14 16:01

niekas


1 Answers

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
like image 111
Daniel Qiu Avatar answered Nov 15 '22 15:11

Daniel Qiu