Python os.path.expanduser() Method



The Python os.path.expanduser() method is used to expand the tilde (~) character in a path string to the user's home directory. It replaces the ~ character with the absolute path to the user's home directory.

If the tilde character is not found or if there is no user's home directory available, the method returns the original path string unchanged.

Syntax

Following is the basic syntax of the Python os.path.expanduser() method −

os.path.expanduser(path)

Parameter

This method accepts a string as a parameter representing the path in which the ~ (tilde) character should be expanded to the user's home directory.

Return Value

The method returns a string representing the path with the ~ (tilde) character expanded to the user's home directory.

Example

In the following example, we are expanding the given file path "path" by replacing the tilde (~) character with the user's home directory using the expanduser() method −

import os
path = "~/Documents/file.txt"
expanded_path = os.path.expanduser(path)
print(expanded_path)  

Output

The output obtained is as follows −

C:\Users\Lenovo/Documents/file.txt

Example

This example demonstartes that if there are multiple tilde (~) symbols in the given path, the expanduser() method only expands the first tilde (~) symbol it encounters and leaves subsequent ones untouched −

import os
path = "~/Documents/~/Downloads"
expanded_path = os.path.expanduser(path)
print(expanded_path) 

Output

Following is the output of the above code −

C:\Users\Lenovo/Documents/~/Downloads

Example

If we provide an empty string as input to the expanduser() method, it returns an empty string −

import os
path = ""
expanded_path = os.path.expanduser(path)
print("The file path is:",expanded_path)     

Output

The result produced is as shown below −

The file path is: 

Example

This example shows that if the tilde character is not found in the given path, the method returns the original path string unchanged −

import os
path = "/home/user/Documents/file.txt"
expanded_path = os.path.expanduser(path)
print(expanded_path)

Output

We get the output as shown below −

/home/user/Documents/file.txt
os_path_methods.htm
Advertisements