0

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'
Barmar
  • 741,623
  • 53
  • 500
  • 612

2 Answers2

5

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

Michael Butscher
  • 10,028
  • 4
  • 24
  • 25
1

$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'])
Barmar
  • 741,623
  • 53
  • 500
  • 612