使用pathlib获取主目录

Ale*_*sky 13 python python-3.4

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

import pathlib
from os import path
p = pathlib.Path(path.expanduser("~"))
Run Code Online (Sandbox Code Playgroud)

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

sim*_*mon 18

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

  • @user9074332——`Path('~username').expanduser()`怎么样?还有`os.path.expanduser('~username')`,但要密切注意如果用户不存在,它们是如何失败的! (3认同)
  • 不同用户的主目录怎么样?(例如不是*您的*主目录) (2认同)

Esp*_*azi 8

对于那些懒得看评论的人:

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


宏杰李*_*宏杰李 7

方法 expanduser()

p = PosixPath('~/films/Monty Python')
p.expanduser()
PosixPath('/home/eric/films/Monty Python')
Run Code Online (Sandbox Code Playgroud)


Ffi*_*ydd 5

看来这个方法是在这里的bug报告中提出来的.编写了一些代码(在这里给出)但不幸的是它似乎没有进入最终的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)))
Run Code Online (Sandbox Code Playgroud)

编辑

这是一个基本的子类型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
Run Code Online (Sandbox Code Playgroud)

  • 这个答案已经过时了。根据 @maf88 使用 `pathlib.Path.home()` (6认同)