Check if the directory is in the path

I am trying to write a Python function to accomplish the following: given a path and directory, return True only if the directory appears somewhere in the path.

For example, consider the following example:

path = 'Documents/Pictures/random/old/test_image.jpg'
dir = 'random'

      

This should return True as the directory random/

happens somewhere along the way. On the other hand, the following example should return False:

path = 'Documents/Pictures/random_pictures/old/test_image.jpg'
dir = 'random`

      

This is because the directory random/

does not appear in the path random_pictures/

does.

Is there a smarter way to do this than just do something like this:

def is_in_directory(path, dir):
    return '/{0}/'.format(dir) in path

      

Perhaps with a module os

or os.path

?

+3


source to share


2 answers


You can use os.path.split

to get the directory path, then strip them and check for existence:

>>> dir = 'random'
>>> dir in os.path.split(path)[0].split('/')
True

      



And as @LittleQ suggested as the best way to split the base path using os.path.sep

>>> dir in os.path.split(path)[0].split(s.path.sep)
True

      

+3


source


using os.path.sep

os.path.dirname :

from os.path import sep,dirname
def is_in_directory(p, d):
    return d in dirname(p).split(sep)

      



os.path.dirname (path) ΒΆ

Return the directory name of the path path. This is the first element of the pair returned by traversing the path to the split () function.

+2


source







All Articles