Search code examples
pythonchdir

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'

Solution

  • $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'])