You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何检查路径是否以指定列表中的任意路径开头?

检查路径是否以列表中任意路径开头

问题场景

目标路径:

S:\Test\Testing\Tested\A\B\C

待匹配路径列表:

include = [r'S:\Test\Testing',
           r'S:\Domino\Testing',
           r'S:\Money\tmp']

需要判断目标路径是否是列表中任意路径的子目录(即路径以列表中的某条路径为前缀),本例中应返回True。

解决方案

直接使用字符串startswith可能出现误判(比如部分字符串匹配但实际不是父目录),推荐用Python内置的路径处理工具:

方法1:os.path模块(兼容Python 2/3)

import os

target_path = r'S:\Test\Testing\Tested\A\B\C'
include = [r'S:\Test\Testing', r'S:\Domino\Testing', r'S:\Money\tmp']

# 统一转为绝对路径,消除相对路径和格式差异
target_abspath = os.path.abspath(target_path)
include_abspaths = [os.path.abspath(p) for p in include]

# 检查是否存在列表路径是目标路径的父目录
match_found = any(os.path.commonpath([target_abspath, p]) == p for p in include_abspaths)
print(match_found)  # 输出:True

方法2:pathlib模块(Python 3.4+ 推荐)

面向对象的路径处理,更简洁直观:

from pathlib import Path

target_path = Path(r'S:\Test\Testing\Tested\A\B\C')
include = [Path(r'S:\Test\Testing'), Path(r'S:\Domino\Testing'), Path(r'S:\Money\tmp')]

# 直接判断目标路径是否是某列表路径的子路径
match_found = any(target_path.is_relative_to(p) for p in include)
print(match_found)  # 输出:True

说明

  • 两种方法都能正确处理Windows路径的大小写不敏感特性、斜杠格式差异(正/反斜杠)以及相对路径问题。
  • 避免用字符串startswith的原因:若列表路径为S:\Test\Test,目标路径为S:\Test\Testing,字符串匹配会误判为True,但实际前者并非后者的父目录。

内容的提问来源于stack exchange,提问作者Eisen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 08:40:29