How to get the home directory in Python?

PythonServer Side ProgrammingProgramming

To get the homedir in python, you can use os.path.expanduser('~') from the os module. This also works if its a part of a longer path like ~/Documents/my_folder/. If there is no ~ in the path, the function will return the path unchanged. You can use it like −

import os
print(os.path.expanduser('~'))

You can also query the environment variables for the HOME variable −

import os
print(os.environ['HOME'])
raja
Updated on 18-Feb-2020 05:30:56

Advertisements