Python中如何判断目录层级关系的方法问题

假设有两个目录 A、B,Python 有模块可以直接判断出 A 是否是 B 的子目录吗?如果没有,只能用正则去进行匹配 dirname 吗?求大神解答并且提供好的方法
Python中如何判断目录层级关系的方法问题

15 回复

os.path.dirname(B) == A
不用正则也可以


在Python里判断目录层级关系,最直接的方法是使用pathlib库的Path对象,它提供了清晰的方法来处理路径。

核心方法是使用Path.is_relative_to()。这个方法在Python 3.9及以上版本可用,能直接判断一个路径是否是另一个路径的子路径。

from pathlib import Path

def is_subpath(parent_path, child_path):
    """
    判断child_path是否是parent_path的子路径(或相同路径)。
    参数可以是字符串或Path对象。
    """
    parent = Path(parent_path).resolve()
    child = Path(child_path).resolve()
    try:
        # is_relative_to 在 child 是 parent 的子路径或相同路径时返回 True
        child.is_relative_to(parent)
        return True
    except (AttributeError, ValueError):
        # 处理低版本Python没有此方法的情况,或无效路径
        return False

# 示例用法
parent = "/usr/local"
child1 = "/usr/local/bin/python"
child2 = "/usr/bin"
child3 = "/usr/local"  # 相同路径

print(is_subpath(parent, child1))  # 输出: True
print(is_subpath(parent, child2))  # 输出: False
print(is_subpath(parent, child3))  # 输出: True

如果你用的Python版本低于3.9,可以用PurePath.relative_to()来模拟这个功能,通过捕获异常来判断。

from pathlib import Path

def is_subpath_legacy(parent_path, child_path):
    parent = Path(parent_path).resolve()
    child = Path(child_path).resolve()
    try:
        # 尝试计算child相对于parent的相对路径
        child.relative_to(parent)
        return True
    except ValueError:
        # 如果抛出ValueError,说明child不是parent的子路径
        return False

# 用法和上面一样

简单总结:用pathlib.Pathis_relative_to()方法最省事。

A.startswith(B) ?


== 这个只能判断父级

AB 均为 fullpath 的话,A in B 吧

import glob; if glob.glob(“B/A”):return True

你这个显然是错的老铁,
C: /a/
B: /a/b/
A: /a/b/c

感觉
os.path.abspath(A).startswith(os.path.abspath(B))

https://gist.github.com/lll9p/4c2a352bda7245236467b19e527616dc

用 pathlib 很方便把。py3.4 以上有。。

py3.4 以下的可以装 pathlib2


受 1L 影响搞错方向

In [6]: c="/a/“

In [7]: b=”/a/b/“

In [8]: a=”/a/b/c"

In [9]: d="/a/c"

In [10]: c in a
Out[10]: True

In [11]: d in a
Out[11]: False

In [12]: b in a
Out[12]: True


B: /b/a/
A: /a/
A in B,但是


U R right

顺便提醒 LZ,如果涉及写操作,还要考虑软硬连接

现在还是在 windows 平台上测试,linux 上测试时候会考虑的

判断 A 是否是 B 的子目录
换句话说,如果路径 B/A 存在,则 A 是 B 的子目录

import os

IS_SUB_DIR = os.path.isdir(os.path.join(‘B’,‘A’))

if IS_SUB_DIR: print(“A is the subdir of B”)

A = ‘/usr/local/abc’
B = '/usr/local’
B == A[:len(B)]

回到顶部