python - 检查目录是否在路径中

标签 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 模块?

最佳答案

您可以使用 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/

相关文章:

Python - 从键列表访问分层字典元素

bash - 如果不存在,bash会创建许多目录

java - 如何更轻松地复制带有子目录的目录?

linux - 只删除文件而不删除 linux 中的目录

python - 获取由标签分隔的文本/BS4

Python 3.x 按列表中的公共(public)元素对二维列表中的元素进行动态分组

python - Matplotlib/Pandas 中条形图的优化

python - 给定列表中项目的组合

linux - ls - 在某些目录中不起作用

python - copytree(),参数 symlink 和ignore 的作用是什么?