Computer >> Computer tutorials >  >> Programming >> Python

How to find the real user home directory using Python?


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

If you're on Python 3.4+, you can also use pathlib module to get the home directory. 

example

from pathlib import Path
print(Path.home())