39

浏览 Python 3.4 中的新pathlib模块,我注意到没有任何简单的方法可以获取用户的主目录。我能想出的获取用户主目录的唯一方法是os.path像这样使用旧的库:

import pathlib
from os import path
p = pathlib.Path(path.expanduser("~"))

这似乎很笨拙。有没有更好的办法?

4

5 回答 5

75

从 python-3.5 开始,有pathlib.Path.home(),这在一定程度上改善了这种情况。

Windows 上的结果是

>>>pathlib.Path.home()
WindowsPath('C:/Users/username')

在 Linux 上

>>>pathlib.Path.home()
PosixPath('/home/username') 
于 2015-10-20T18:43:22.700 回答
24

方法 expanduser()

p = PosixPath('~/films/Monty Python')
p.expanduser()
PosixPath('/home/eric/films/Monty Python')
于 2017-01-01T11:37:10.727 回答
6

对于懒得看评论的人:

现在有pathlib.Path.home方法了。

于 2021-03-04T11:39:21.090 回答
5

似乎这个方法是在这里的错误报告中提出的。编写了一些代码(在此处给出),但不幸的是,它似乎没有进入最终的 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
于 2014-04-08T20:47:41.627 回答
-2

警告:这个答案是 3.4 特定的。正如其他答案中所指出的,此功能是在以后的版本中添加的。

看起来没有更好的方法可以做到这一点。我只是搜索了文档,但没有找到与我的搜索词相关的内容。

  • ~有零点击
  • expand有零点击
  • user有 1 次命中作为返回值Path.owner()
  • relative有 8 次点击,主要与PurePath.relative_to()
于 2014-04-08T20:49:49.707 回答