使用pathlib获取主目录

问题描述 投票:9回答:4

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

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

这看起来很笨重。有没有更好的办法?

python python-3.4
4个回答
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)))

EDIT

这是一个基本的子类型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

13
投票

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


4
投票

method expanduser()

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

-1
投票

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

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

  • ~没有命中
  • expand没有命中
  • user有1次击中作为Path.owner()的回报值
  • relative有8个安打,主要与PurePath.relative_to()有关
© www.soinside.com 2019 - 2024. All rights reserved.