How to find the real user home directory using Python?



On a multiuser operating system, a home directory is a file system location that holds the files specific to a particular user.

A login directory is another name for a home directory.You may obtain the home directory using Python in a number of ways.

Using os module

The os.path.expanduser() function in Python provides the most straightforward method for retrieving the user home directory across all platforms. The Python os module offers os.path.expanduser(") to retrieve the home directory. This also functions if it is a part of a longer path. The function will return the path unchanged if there is no ~ in the path.

Example - Home Directory Path

Following is an example to find the home directory using os.path.expanduser() function −

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

Output

Following is an output of the above code −

C:\Users\Lenovo

Example - File Inside Home Directory

Use os.path.join to create the path C:\Users\Lenovo\Downloads\Works −

import os home_directory = os.path.expanduser( '~' ) path = os.path.join( home_directory, 'Documents', 'mysql_access' ) print( path )

Output

Following is an output of the above code 

C:\Users\Lenovo\Documents\mysql_access

Example - ~ Substitution

If you already have a string path, such as C:\Users\Lenovo\Downloads\Works, where you wish to replace with the home directory path, you can put it in directly to.expanduser() instead of using the safe way to generate paths, which is os.path.join() −

import os path = os.path.expanduser('~\Documents\mysql_access') print( path )

Output

Following is an output of the above code −

C:\Users\Lenovo\Documents\mysql_accessy

Using pathlib module

The pathlib module in Python can also be used to obtain the user's home directory.

Example - Home Directory Path

Following is an example to find the home directory path.home() function −

from pathlib import Path home_directory = Path.home() print( f'Path: { home_directory} !' )

Output

Following is an output of the above code −

Path: C:\Users\Lenovo !

Example - File Inside Home Directory

Using.joinpath, you can also quickly create paths inside the user's home directory () −

from pathlib import Path path = Path.home().joinpath( 'Documents', 'mysql_access' ) print(path)

Output

Following is an output of the above code −

C:\Users\Lenovo\Documents\mysql_access

Example - ~ Substitution

Use.expanduser() if you already have a string path, such as /Documents/mysql_access, where you want to replace with the path to your home directory −

from pathlib import Path path_string = '~\Documents\mysql_access' path = Path(path_string).expanduser() print(path)

Output

Following is an output of the above code −

C:\Users\Lenovo\Documents\mysql_access

Advertisements