【问题标题】:Getting Home Directory with pathlib使用 pathlib 获取主目录
【发布时间】:2014-04-08 20:25:18
【问题描述】:

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

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

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

【问题讨论】:

标签: python python-3.4


【解决方案1】:

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

Windows 上的结果是

>>>pathlib.Path.home()
WindowsPath('C:/Users/username')

在 Linux 上

>>>pathlib.Path.home()
PosixPath('/home/username') 

【讨论】:

  • 不同用户的主目录呢? (例如,不是您的主目录)
  • @user9074332 -- Path('~username').expanduser() 怎么样?还有os.path.expanduser('~username'),但如果用户不存在,请密切注意这些如何失败!
  • 这应该是 2021 年的答案。干净简单。
【解决方案2】:

methodexpanduser():

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

【讨论】:

    【解决方案3】:

    对于懒惰阅读的人the comments

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

    【讨论】:

      【解决方案4】:

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

      【讨论】:

      • 我添加了一个基本的子类,它提供了一个expanduser 方法。
      • 这个答案已经过时了。每个@maf88 使用pathlib.Path.home()
      【解决方案5】:

      警告:这个答案是 3.4 特定的。正如其他答案中所指出的,此功能是在以后的版本中添加的。

      似乎没有更好的方法可以做到这一点。我刚刚搜索了the documentation,没有找到与我的搜索词相关的内容。

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

      【讨论】:

        猜你喜欢
        • 2022-07-27
        • 2015-12-18
        • 2017-06-04
        • 1970-01-01
        • 1970-01-01
        • 2019-06-20
        • 2018-10-15
        • 2011-12-16
        • 2018-11-15
        相关资源
        最近更新 更多