简体   繁体   中英

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.
I found the os.chdir() to change the programs working directory. Now I need to learn how to access the current user's environment variables such as $HOME.

One contributor said that user.info contains the home directory, but I haven't found how to obtain that. 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

$HOME and ~ are shell syntax that expands into the user's home directory, not actual directory names by themselves.

Use os.environ to access environment variables in Python:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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