[英]Check whether or not directory is in path
我正在尝试编写一个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/
does。
有没有更聪明的方法来做到这一点,而不仅仅是做这样的事情:
def is_in_directory(path, dir):
return '/{0}/'.format(dir) in path
也许使用os
或os.path
模块?
您可以使用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
使用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()返回的对中的第一个元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.