检查目录是否在路径中

时间:2015-06-22 19:56:48

标签: python directory

我尝试编写Python函数来完成以下操作:给定路径和目录,只有当目录出现在路径中的某个位置时才返回True。

例如,请考虑以下示例:

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

这应该返回True,因为目录random/出现在路径的某个位置。另一方面,以下示例应返回False:

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

这是因为目录random/未显示在路径random_pictures/中。

有没有更聪明的方法来做到这一点,而不仅仅是做这样的事情:

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

也许使用osos.path模块?

2 个答案:

答案 0 :(得分:3)

您可以使用os.path.split获取目录路径,然后拆分它们并检查是否存在:

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

正如@LittleQ建议的更好的方法,您可以使用os.path.sep

拆分基本路径
>>> dir in os.path.split(path)[0].split(s.path.sep)
True

答案 1 :(得分:2)

使用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(路径)¶

  

返回路径名路径的目录名称。这是通过将路径传递给函数split()返回的对中的第一个元素。

相关问题