【问题标题】:Find a path in Windows relative to another在 Windows 中查找相对于另一个的路径
【发布时间】:2010-12-11 21:32:49
【问题描述】:

这个问题应该是不费吹灰之力的,但我还没有解决。

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

这里作为一个尝试的实现,完成了几个文档测试,练习了一些示例用例(并演示了它失败的地方)。 runnable script is also available on my source code repository,但它可能会改变。如果没有提供参数,runnable 脚本将运行 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 中的 cmets 可以看出,当 start 指定驱动器号并且目标相对于驱动器的根目录时,此实现失败。

这带来了几个问题

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

【问题讨论】:

    标签: python windows filesystems relative-path


    【解决方案1】:

    我同意你的看法:这似乎是 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 才能让它工作......)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-08
      • 2012-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-21
      • 1970-01-01
      相关资源
      最近更新 更多