我正在尝试编写一个 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
也许使用 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
关于python - 检查目录是否在路径中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30988700/