python - 在 Windows 中查找相对于另一个的路径

标签 python windows filesystems relative-path

这个问题应该很简单,但我还没能解决。

我需要一个带有两个参数的函数,每个参数一个文件路径,相对或绝对路径,并返回一个文件路径,该文件路径是相对于第二个路径(开始)解析的第一个路径(目标)。解析的路径可能是相对于当前目录的,也可能是绝对的(我不在乎)。

这里作为一个尝试性的实现,完成了几个文档测试,练习了一些示例用例(并演示了它失败的地方)。 runnable script is also available on my source code repository , 但它可能会改变。如果没有提供参数,可运行脚本将运行 doctest,或者如果提供,将传递一个或两个参数给 findpath。

def findpath(target, start=os.path.curdir):
    r"""
    Find a path from start to target where target is relative to start.

    >>> orig_wd = os.getcwd()
    >>> os.chdir('c:\\windows') # so we know what the working directory is

    >>> findpath('d:\\')
    'd:\\'

    >>> findpath('d:\\', 'c:\\windows')
    'd:\\'

    >>> findpath('\\bar', 'd:\\')
    'd:\\bar'

    >>> findpath('\\bar', 'd:\\foo') # fails with '\\bar'
    'd:\\bar'

    >>> findpath('bar', 'd:\\foo')
    'd:\\foo\\bar'

    >>> findpath('bar\\baz', 'd:\\foo')
    'd:\\foo\\bar\\baz'

    >>> findpath('\\baz', 'd:\\foo\\bar') # fails with '\\baz'
    'd:\\baz'

    Since we're on the C drive, findpath may be allowed to return
    relative paths for targets on the same drive. I use abspath to
    confirm that the ultimate target is what we expect.
    >>> os.path.abspath(findpath('\\bar'))
    'c:\\bar'

    >>> os.path.abspath(findpath('bar'))
    'c:\\windows\\bar'

    >>> findpath('..', 'd:\\foo\\bar')
    'd:\\foo'

    >>> findpath('..\\bar', 'd:\\foo')
    'd:\\bar'

    The parent of the root directory is the root directory.
    >>> findpath('..', 'd:\\')
    'd:\\'

    restore the original working directory
    >>> os.chdir(orig_wd)
    """
    return os.path.normpath(os.path.join(start, target))

从doctest中的注释可以看出,当start指定盘符且target相对于盘根时,此实现失败。

这带来了几个问题

  1. 这种行为是 os.path.join 的限制吗?换句话说,os.path.join('d:\foo', '\bar') 应该解析为 'd:\bar' 吗?作为 Windows 用户,我倾向于这样认为,但我不愿意认为像 path.join 这样的成熟函数需要更改才能处理这种用例。
  2. 是否有适用于所有这些测试用例的现有目标路径解析器示例,例如 findpath?
  3. 如果对上述问题回答“否”,您将如何实现这种期望的行为?

最佳答案

我同意你的看法:这似乎是 os.path.join 中的一个缺陷。看起来你必须单独处理驱动器。此代码通过了所有测试:

def findpath(target, start=os.path.curdir):
    sdrive, start = os.path.splitdrive(start)
    tdrive, target = os.path.splitdrive(target)
    rdrive = tdrive or sdrive
    return os.path.normpath(os.path.join(rdrive, os.path.join(start, target)))

(是的,我必须嵌套两个 os.path.join 才能让它工作...)

关于python - 在 Windows 中查找相对于另一个的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1654659/

相关文章:

Python:从列表中元组内的字典中获取字典值并用它做一些事情

python - 如何在 Pandas 数据框中按名称选择行列表

python - Pandas - 当一项不同时标记

powershell - 列出所有不包含通配符匹配文件的目录

Python 字典内的列表理解

windows - 公开暴露本地[ASP Web-] API

c++ - cmake:如何编写CMakeLists.txt以便于将Linux上的程序移植到Windows上?

c# - 如何从 C# 启动 windows "run"对话框

windows - 是否有任何支持加密的 Windows 开源文件系统?

c++ - 来自 ExpandEnvironmentStrings 的本地化值