【问题标题】:How do I change the current working directory of a Python program to the user's home directory?如何将 Python 程序的当前工作目录更改为用户的主目录?
【发布时间】:2019-07-16 01:15:43
【问题描述】:

我在 MacOS 10.14.5 上使用 python 3.7.3。
我找到了 os.chdir() 来更改程序工作目录。现在我需要学习如何访问当前用户的环境变量,例如 $HOME。

一位贡献者说 user.info 包含主目录,但我还没有找到如何获得它。谢谢。

这些不起作用::-)

os.chdir("$HOME")
os.chdir("~")

os.chdir("$HOME")
FileNotFoundError: [Errno 2] No such file or directory: '$HOME'

【问题讨论】:

    标签: python chdir


    【解决方案1】:

    使用

    os.chdir(os.path.expanduser("~"))
    

    函数os.path.expanduser用用户目录替换波浪号,适用于Unix/Linux和Windows

    【讨论】:

      【解决方案2】:

      $HOME~ 是扩展至用户主目录的 shell 语法,而不是它们本身的实际目录名称。

      在 Python 中使用os.environ 访问环境变量:

      os.chdir(os.environ['HOME'])
      

      【讨论】:

      • 完美,正是我想要的。非常感谢。我现在将更多地研究 os.environ。
      猜你喜欢
      • 2014-12-02
      • 2015-02-22
      • 1970-01-01
      • 2014-01-14
      • 1970-01-01
      • 2012-07-22
      • 2015-01-17
      • 2011-07-19
      • 1970-01-01
      相关资源
      最近更新 更多