浏览 Python 3.4 中的新pathlib
模块,我注意到没有任何简单的方法可以获取用户的主目录。我能想出的获取用户主目录的唯一方法是os.path
像这样使用旧的库:
import pathlib
from os import path
p = pathlib.Path(path.expanduser("~"))
这似乎很笨拙。有没有更好的办法?
浏览 Python 3.4 中的新pathlib
模块,我注意到没有任何简单的方法可以获取用户的主目录。我能想出的获取用户主目录的唯一方法是os.path
像这样使用旧的库:
import pathlib
from os import path
p = pathlib.Path(path.expanduser("~"))
这似乎很笨拙。有没有更好的办法?
从 python-3.5 开始,有pathlib.Path.home()
,这在一定程度上改善了这种情况。
Windows 上的结果是
>>>pathlib.Path.home()
WindowsPath('C:/Users/username')
在 Linux 上
>>>pathlib.Path.home()
PosixPath('/home/username')
有方法 expanduser()
:
p = PosixPath('~/films/Monty Python')
p.expanduser()
PosixPath('/home/eric/films/Monty Python')
对于懒得看评论的人:
现在有pathlib.Path.home
方法了。
似乎这个方法是在这里的错误报告中提出的。编写了一些代码(在此处给出),但不幸的是,它似乎没有进入最终的 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
警告:这个答案是 3.4 特定的。正如其他答案中所指出的,此功能是在以后的版本中添加的。
看起来没有更好的方法可以做到这一点。我只是搜索了文档,但没有找到与我的搜索词相关的内容。
~
有零点击expand
有零点击user
有 1 次命中作为返回值Path.owner()
relative
有 8 次点击,主要与PurePath.relative_to()