使用pathlib获取主目录

时间:2014-04-08 20:25:18

标签: python python-3.4

通过Python 3.4中的新pathlib模块,我注意到没有任何简单的方法来获取用户的主目录。获取用户主目录的唯一方法是使用较旧的os.path lib,如下所示:

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

这看起来很笨重。还有更好的方法吗?

5 个答案:

答案 0 :(得分:13)

从python-3.5开始,有Path.home(),这有点改善了这种情况。

答案 1 :(得分:5)

似乎这个方法是在错误报告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

答案 2 :(得分:3)

method expanduser()

p = PosixPath('~/films/Monty Python')
p.expanduser()
PosixPath('/home/eric/films/Monty Python')

答案 3 :(得分:0)

对于懒惰阅读的人the comments

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

答案 4 :(得分:-1)

警告:这个答案是3.4具体的。正如其他答案中所指出的,此功能已在更高版本中添加。

看起来没有更好的方法来做到这一点。我刚刚搜索了the documentation,我的搜索字词没有任何相关内容。

  • ~点击次数为
  • expand点击次数为
  • user有1次点击作为Path.owner()
  • 的返回值
  • relative有8个匹配,主要与PurePath.relative_to()
  • 相关
相关问题