通过Python 3.4中的新pathlib
模块,我注意到没有任何简单的方法来获取用户的主目录。获取用户主目录的唯一方法是使用较旧的os.path
lib,如下所示:
import pathlib
from os import path
p = pathlib.Path(path.expanduser("~"))
这看起来很笨重。有没有更好的办法?
似乎这个方法是在一个错误报告here中提出的。编写了一些代码(给定here)但不幸的是它似乎没有进入最终的Python 3.4版本。
顺便提一下,提出的代码与您在问题中的代码非常相似:
# As a method of a Path object
def expanduser(self):
""" Return a new path with expanded ~ and ~user constructs
(as returned by os.path.expanduser)
"""
return self.__class__(os.path.expanduser(str(self)))
这是一个基本的子类型PathTest
,其子类WindowsPath
(我在Windows的盒子上,但你可以用PosixPath
替换它)。它根据错误报告中提交的代码添加了classmethod
。
from pathlib import WindowsPath
import os.path
class PathTest(WindowsPath):
def __new__(cls, *args, **kwargs):
return super(PathTest, cls).__new__(cls, *args, **kwargs)
@classmethod
def expanduser(cls):
""" Return a new path with expanded ~ and ~user constructs
(as returned by os.path.expanduser)
"""
return cls(os.path.expanduser('~'))
p = PathTest('C:/')
print(p) # 'C:/'
q = PathTest.expanduser()
print(q) # C:\Users\Username
从python-3.5开始,有Path.home()
,它在某种程度上改善了这种情况。
有method expanduser()
:
p = PosixPath('~/films/Monty Python')
p.expanduser()
PosixPath('/home/eric/films/Monty Python')
警告:这个答案是3.4具体的。正如其他答案所指出的,此功能已在更高版本中添加。
看起来没有更好的方法来做到这一点。我刚刚搜索了the documentation,我的搜索字词没有任何相关内容。
~
没有命中expand
没有命中user
有1次击中作为Path.owner()
的回报值relative
有8个安打,主要与PurePath.relative_to()
有关