
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get the Home Directory in Python
When we are building Python applications that store or retrieve user-specific files and settings, then we will often need to access the home directory. The home directory is the default location on a computer where user-related data is stored, such as documents, configuration files, and application data.
Python provides simple and cross-platform ways of finding the home directory programmatically by making it easy to write code that works on Windows, macOS, and Linux without modifications.
In this article, we'll explore the different methods to get the home directory in Python.
Using os.path.expanduser("~")
The os.path.expanduser() is a function in Python's built-in os.path module. When we assign the ~ character to the expanduser() function, it returns a user's home directory.
Example
Here in this example, we are getting the user's home directory by passing the symbol ~ to the function os.path.expanduser() -
import os home_directory = os.path.expanduser("~") print(home_directory)
Following is the output of the above program -
C:\Users\91970
Using Path.home()
Path.home() is a method available in Python's built-in module pathlib. This module returns the home directory of the current user as a Path object, which is part of Python's object-oriented approach to file system paths.
Example
Following is the example, in which we are obtaining the user's home directory by calling the Path.home() method -
from pathlib import Path home_directory = Path.home() print(home_directory)
Following is the output of the above program ?
C:\Users\91970
Using os.environ['HOME']
The os.environ['HOME'] is another method to access the HOME environment variable using Python's built-in os module. This method directly retrieves the path to the current user's home directory on Unix-based systems such as Linux and macOS.
Example
Following is the example which shows how to get the current user's home directory by accessing the HOME environment variable using the os.environ() method -
import os home_directory = os.environ['HOME'] print(home_directory)
Following is the output of the above program -
C:\Users\91970
Note: When we execute the above program on Windows OS, it will raise an error. We can use os.environ.get() method to access the current user's home directory.
Below is the example in which we pass the parameter USERPROFILE to the function os.environ.get() to get the home directory on Windows operating system -
import os home_dir = os.environ.get('USERPROFILE') print(home_dir)
Following is the output of the above program -
C:\Users\91970