Signup/Sign In
PUBLISHED ON: FEBRUARY 23, 2021

How to get the home directory in Python

In this article, we will learn how to get the path of the home directory in Python. We will use two built-in functions to get the home directory.

The home directory contains multiple files for a given user of the system. Look at the two below scripts to get the home directory in Python. We will look at two different modules of Python such as the os module and pathlib module.

Use os module to get the Home Directory

os module provides os.path.expanduser('~') to get the home directory in Python. This also works if it is a part of a longer path like ~/Documents/my_folder/. If there is no ~ in the path, the function will return the path unchanged. This function is recommended because it works on both Unix and Windows. It returns the argument with an initial component of (tilt) ~ or ~user replaced by the user’s home address.

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


C:\Users\Yukti

Use the pathlib module to get the Home Directory

The pathlib module provides path.home() to get the home directory in Python. This function works fine if your Python version is Python 3.4+. It returns a new path object having the user’s home directory.

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


C:\Users\Yukti

Conclusion

In this article, we learned two different ways to get the home directory of a user's system in Python. One way was using os.path.expanduser('~') and another way was pathlib.Path.home(). Do check your script to avoid errors.



About the author:
An enthusiastic fresher, a patient person who loves to work in diverse fields. I am a creative person and always present the work with utmost perfection.