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()一些改善了这种情况.
有方法 expanduser():
p = PosixPath('~/films/Monty Python')
p.expanduser()
PosixPath('/home/eric/films/Monty Python')
Run Code Online (Sandbox Code Playgroud)
看来这个方法是在这里的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)
| 归档时间: |
|
| 查看次数: |
6261 次 |
| 最近记录: |