简体   繁体   English

如何将Python程序的当前工作目录更改为用户的主目录?

[英]How do I change the current working directory of a Python program to the user's home directory?

I'm in python 3.7.3 on MacOS 10.14.5. 我在MacOS 10.14.5上的python 3.7.3中。
I found the os.chdir() to change the programs working directory. 我发现os.chdir()更改了程序的工作目录。 Now I need to learn how to access the current user's environment variables such as $HOME. 现在,我需要学习如何访问当前用户的环境变量,例如$ HOME。

One contributor said that user.info contains the home directory, but I haven't found how to obtain that. 一位撰稿人说user.info包含主目录,但我还没有找到如何获得它。 Thank you. 谢谢。

These don't work: :-) 这些不起作用::-)

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

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

Use 采用

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

The function os.path.expanduser replaces the tilde with the user directory and works on Unix/Linux and Windows 函数os.path.expanduser将波浪号替换为用户目录,并在Unix / Linux和Windows上运行

$HOME and ~ are shell syntax that expands into the user's home directory, not actual directory names by themselves. $HOME~是shell语法,它们会扩展到用户的主目录,而不是本身的实际目录名。

Use os.environ to access environment variables in Python: 使用os.environ在Python中访问环境变量:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM