【问题标题】:Python: How to check if path is a subpath [duplicate]Python:如何检查路径是否是子路径
【发布时间】:2014-02-20 02:58:38
【问题描述】:

假设我有这些路径:

/tmp/a
/tmp/abc
/tmp/abc/d/my_file.py

如何检查/tmp/abc/d/my_file.py 是否是/tmp/abc 的子路径?我试过了:

file_path.startswith(dir_path)

但它为/tmp/a 目录返回True,而my_file.py 不在其中。

【问题讨论】:

    标签: python python-2.7 directory


    【解决方案1】:

    试试这个: file_path.startswith(os.path.abspath(dir_path)+os.sep)

    你也可以检查一下: How to check whether a directory is a sub directory of another directory

    所以你的例子:

    >>> '/tmp/abc/d/my_file.py'.startswith(os.path.abspath('/tmp/abc')+os.sep)
    True
    >>> '/tmp/abc/d/my_file.py'.startswith(os.path.abspath('/tmp/a')+os.sep)
    False
    

    【讨论】:

    • 可能想检查是file_path.startswith(os.path.abspath(dir_path)+os.sep)还是file_path == dir_path
    • 此解决方案可能会引入一些安全问题,因为它没有考虑目录遍历(在路径中添加多个 '..')。您应该比较 os.path.realpath() 的结果。
    • @AndreasKraft 为什么是realpath vs normpath?
    • normpath() 还规范化操作系统表示的路径。这意味着,例如,在 Windows 下使用“\”作为分隔符,这再次使其在比较中更难使用。
    猜你喜欢
    • 2011-12-26
    • 2016-08-18
    • 1970-01-01
    • 1970-01-01
    • 2014-03-09
    • 2011-10-16
    • 2014-05-05
    • 2011-11-25
    相关资源
    最近更新 更多