简体   繁体   English

检查目录是否在路径中

[英]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. 我正在尝试编写一个Python函数来完成以下操作:给定一个路径和目录,只有当目录出现在路径中的某个位置时才返回True。

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. 这应该返回True,因为目录random/出现在路径的某个地方。 On the other hand, the following example should return False: 另一方面,以下示例应返回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. 这是因为目录random/没有出现在路径中, 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? 也许使用osos.path模块?

You can use os.path.split to get the directory path then split them and check for existence : 您可以使用os.path.split获取目录路径,然后拆分它们并检查是否存在:

>>> 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 正如@LittleQ建议的那样,您可以使用os.path.sep拆分基本路径

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

split using os.path.sep os.path.dirname : 使用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)¶ os.path.dirname(路径)¶

Return the directory name of pathname path. 返回路径名路径的目录名称。 This is the first element of the pair returned by passing path to the function split(). 这是通过将路径传递给函数split()返回的对中的第一个元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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