简体   繁体   中英

Check whether or not directory is in path

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

For example consider the following example:

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

This should return True, since the directory random/ occurs somewhere along the path. 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 simply doing something like this:

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

Perhaps with an os or os.path module?

You can use os.path.split to get the directory path then split them and check for existence :

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

And as @LittleQ suggested as a better way you can split your base path with os.path.sep

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

split 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 pathname path. This is the first element of the pair returned by passing path to the function split().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM