How to get absolute path of a pathlib.Path object?

后端 未结 4 1225
暗喜
暗喜 2021-02-03 16:56

Making a path object with pathlib module like:

p = pathlib.Path(\'file.txt\')

The p object will point to some file in

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-03 17:25

    You're looking for the method .absolute, if my understanding is correct, whose documentation states:

    >>> print(p.absolute.__doc__)
    Return an absolute version of this path.  This function works
            even if the path doesn't point to anything.
    
            No normalization is done, i.e. all '.' and '..' will be kept along.
            Use resolve() to get the canonical path to a file.
    

    With a test file on my system this returns:

    >>> p = pathlib.Path('testfile')
    >>> p.absolute()
    PosixPath('/home/jim/testfile')
    

    This method seems to be a new, and still, undocumented addition to Path and Path inheritting objects.

    Created an issue to document this.

提交回复
热议问题