Python get home directory [Practical Examples]


Python

Author: Bashir Alam
Reviewer: Deepak Prasad

 

Introduction to Python get home directory

Directories are a way of storing, organizing, and separating files on a computer. The path contains a combination of directory names, folder names separated by slashes and colons and this gives the route to a file in the system. The home directory contains multiple files for a given user of the system. In this tutorial, we will learn how we can use find home directory in Python using different ways and various examples. We will discuss two main libraries that can be used to find the home directory in Python including OS and pathlib.

In a nutshell, this tutorial will contain all the necessary modules and methods that you can use to find the home directory and perform different operations with python directories.

 

Getting started with Python get home directory

As we have already discussed, a directory is a way to store and organize files. The directory that does not have a parent is called a root directory. The way to reach the file is called the path. The path contains a combination of directory names, folder names separated by slashes and colons and this gives the route to a file in the system.

Python contains several modules that have a number of built-in functions to manipulate and process data. Python has also provided modules that help us to interact with the operating system and the files. In the upcoming sections, we will use the OS and pathlib module to perform various operations on python directories including getting the home directory.

 

Method-1: Python get home directory using OS module

The OS module in Python provides functions for interacting with the operating system. OS comes under Python's standard utility modules. This module provides a portable way of using operating system dependent functionality. The os and os. path modules include many functions to interact with the file system. We can get access to the OS module’s functionalities by importing it as shown below:

import os

he 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/.

In the next section, we will use this method in various examples to get the home directory.

 

Example-1  Python get home directory using OS module without argument

Now let us discuss the os.path.expanduser() method in more detail by taking examples. The following is the simple syntax of getting the home directory in python using os module.

os.path.expanduser(‘~’)

Notice that this method takes on mandatory arguments. If we run the program without providing the argument, then it will return an error. See the example below:

# Importing OS module
import os
# Python get home directory using os module
print(os.path.expanduser())

Output:

Python get home directory

Notice that the error clearly says that our function is missing one required argument for Path.

 

Example-2 Python get home directory using OS module with an argument

Now, see the following program which successfully prints out the home directory.

# Importing OS module
import os
# printing
print("The HOME directory is :")
# Python get home directory using os module
print(os.path.expanduser("~"))

Output:

The HOME directory is :
/home/uca

Now if we provide any other argument instead of a tilted dash, this method will return it as it is. See the python program below:

# Importing OS module
import os
# printing
print("The HOME directory is :")
# Python get home directory using os module
print(os.path.expanduser("+++++++"))

Output:

The HOME directory is :
<+++++++

See the example below again:

# Importing OS module
import os
# printing
print("The HOME directory is :")
# Python get home directory using os module
print(os.path.expanduser("Invalid argument provided"))

Output:

The HOME directory is :
Invalid argument provided

So it is mandatory to provide ‘~’ as an argument to the os.path.expanduser() method to get the correct home directory. Otherwise, this method will either return an error or will just return the argument as it is.

 

Example-3 Python get home directory using environ method

Another method to get the home directory is to use the os.environ bypassing ‘HOME’ to it as a key value. See the example below which prints out the home directory.

# importing os module
import os
# printing
print("The home directory is:")
# Python get home directory using os module
print(os.environ['HOME'])

Output:

The home directory is:
/home/uca

If we do not specify ‘HOME’ and run then it will print all the available environmental variables. See the example below:

# importing os module
import os
# Python environ
print(os.environ)

Output:

environ({'SHELL': '/bin/bash', 'SESSION_MANAGER': 'local/UCA-NAR-NBK:@/tmp/.ICE-unix/2479,unix/UCA-NAR-NBK:/tmp/.ICE-unix/2479', 'QT_ACCESSIBILITY': '1', 'COLORTERM': 'truecolor', 'XDG_CONFIG_DIRS': '/etc/xdg/xdg-ubuntu:/etc/xdg', 'XDG_MENU_PREFIX': 'gnome-', 'TERM_PROGRAM_VERSION': '1.63.0', 'GNOME_DESKTOP_SESSION_ID': 'this-is-deprecated', 'LC_ADDRESS': 'ky_KG', 'JAVA_HOME': '/usr/lib/jvm/jdk-11.0.10', 'GNOME_SHELL_SESSION_MODE': 'ubuntu', 'LC_NAME': 'ky_KG', 'SSH_AUTH_SOCK': '/run/user/1000/keyring/ssh', 'BREAKPAD_DUMP_LOCATION': '/home/uca/.config/Code/exthost Crash Reports', 'XMODIFIERS': '@im=ibus', 'DESKTOP_SESSION': 'ubuntu', 'LC_MONETARY': 'ky_KG', 'SSH_AGENT_PID': '2431', 'GTK_MODULES': 'gail:atk-bridge', 'PWD': '/home/uca/Downloads/python', 'XDG_SESSION_DESKTOP': 'ubuntu', 'LOGNAME': 'uca', 'XDG_SESSION_TYPE': 'x11', 'GPG_AGENT_INFO': '/run/user/1000/gnupg/S.gpg-agent:0:1', 'XAUTHORITY': '/run/user/1000/gdm/Xauthority', 'VSCODE_GIT_ASKPASS_NODE': '/usr/share/code/code', 'GJS_DEBUG_TOPICS': 'JS ERROR;JS LOG', 'WINDOWPATH': '2', 'HOME': '/home/uca', 'USERNAME': 'uca', 'IM_CONFIG_PHASE': '1', 'LC_PAPER': 'ky_KG', 'LANG': 'en_US.UTF-8', 'LS_COLORS': 'rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=00:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.zst=01;31:*.tzst=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.wim=01;31:*.swm=01;31:*.dwm=01;31:*.esd=01;31:*.jpg=01;35:*.jpeg=01;35:*.mjpg=01;35:*.mjpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.m4a=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.oga=00;36:*.opus=00;36:*.spx=00;36:*.xspf=00;36:', 'XDG_CURRENT_DESKTOP': 'Unity', 'GIT_ASKPASS': '/usr/share/code/resources/app/extensions/git/dist/askpass.sh', 'INVOCATION_ID': 'ae8a214b22cd429f9405d4011cb471d8', 'MANAGERPID': '2248', 'CHROME_DESKTOP': 'code-url-handler.desktop', 'GJS_DEBUG_OUTPUT': 'stderr', 'VSCODE_GIT_ASKPASS_EXTRA_ARGS': '--ms-enable-electron-run-as-node', 'LESSCLOSE': '/usr/bin/lesspipe %s %s', 'XDG_SESSION_CLASS': 'user', 'TERM': 'xterm-256color', 'LC_IDENTIFICATION': 'ky_KG', 'LESSOPEN': '| /usr/bin/lesspipe %s', 'USER': 'uca', 'VSCODE_GIT_IPC_HANDLE': '/run/user/1000/vscode-git-eff433ace4.sock', 'DISPLAY': ':0', 'SHLVL': '1', 'LC_TELEPHONE': 'ky_KG', 'QT_IM_MODULE': 'ibus', 'LC_MEASUREMENT': 'ky_KG', 'XDG_RUNTIME_DIR': '/run/user/1000', 'LC_TIME': 'ky_KG', 'VSCODE_GIT_ASKPASS_MAIN': '/usr/share/code/resources/app/extensions/git/dist/askpass-main.js', 'JOURNAL_STREAM': '8:59571', 'XDG_DATA_DIRS': '/usr/share/ubuntu:/usr/local/share/:/usr/share/:/var/lib/snapd/desktop', 'GDK_BACKEND': 'x11', 'PATH': '/home/uca/anaconda3/bin:/home/uca/.local/bin:/home/uca/anaconda3/bin:/home/uca/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin', 'GDMSESSION': 'ubuntu', 'ORIGINAL_XDG_CURRENT_DESKTOP': 'ubuntu:GNOME', 'DBUS_SESSION_BUS_ADDRESS': 'unix:path=/run/user/1000/bus', 'GIO_LAUNCHED_DESKTOP_FILE_PID': '40955', 'GIO_LAUNCHED_DESKTOP_FILE': '/usr/share/applications/code.desktop', 'LC_NUMERIC': 'ky_KG', 'TERM_PROGRAM': 'vscode', '_': '/usr/bin/python3'})

This method returns a dictionary of all the available environment variables in our system. So by providing ‘HOME’ as a key we were able to get access to the home directory.

 

Method-2: Python get home directory using Pathlib module

Pathlib is an object-oriented interface to the filesystem and provides a more intuitive method to interact with the filesystem in a platform-agnostic and pythonic manner. This library is included in all versions of python >= 3.4. The pathlib is a Python module that provides an object API for working with files and directories. The pathlib is a standard module. This module has many useful methods which help us to perform various operations on directories. One of the methods is Path.home() which is used to get the home directory. The following is the simple syntax to find the home directory.

from pathlib import Path
Path.home()

Notice that this method does not require any argument. In the upcoming section, we will take examples and see how we can use this module to find the Home directory in Python

 

Example of Python get home directory using Pathlib module

The Path.home() method in the pathlib module is used to find the home directory. Now let us take an example and see how we can find the home directory using this method. See the python example below:

# importing Path from pathlib
from pathlib import Path
# print
print("The home directory is:")
# Python get home directory using pathlib
print(Path.home())

Output:

The home directory is:
/home/uca

Notice that this method does not require any argument.

 

Summary

Directories are a way of storing, organizing, and separating files on a computer. In this tutorial, we learned how to get the home directory by using various methods. We covered three different methods that we can use to get the home directory including os.path.expanduser(‘~’), os.environ(), and Path.home() methods by taking various examples. To summarize, this tutorial contains all the necessary and important methods that are required to get the python home directory.

 

Further Reading

Python directory
Python OS module
Python pathlib

 

Bashir Alam

Bashir Alam

He is a Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in Python, Java, Machine Learning, OCR, text extraction, data preprocessing, and predictive models. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment