Python os.path.expandvars() Method



The Python os.path.expandvars() method is used to expand environment variables in a path string. It takes a path containing environment variables in the format $VARIABLE or ${VARIABLE} and replaces them with their corresponding values from the environment.

If an environment variable referenced in the path string is not defined, the expandvars() method replaces the reference with an empty string. If the path string does not contain any environment variable references, the method returns the original path string unchanged.

Syntax

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

os.path.expandvars(path)

Parameter

This method accepts a string as a parameter representing the path in which environment variables should be expanded.

Return Value

The method returns a string representing the path with environment variables expanded.

Example

In the following example, we are expanding the given file path "path" by replacing the "$HOME" environment variable with the corresponding value, which is the user's home directory using the expandvars() method −

import os
path = "$HOME/Documents/file.txt"
expanded_path = os.path.expandvars(path)
print(expanded_path)   

Output

The output obtained is as follows −

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

Example

Here, we are expanding the Windows path by replacing the "%USERNAME%" environment variable with the corresponding value, which is the username −

import os
path = "C:\\Users\\%USERNAME%\\Documents\\file.txt"
expanded_path = os.path.expandvars(path)
print(expanded_path)   

Output

Following is the output of the above code −

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

Example

If the environment variable specified does not exist, the path remains unchanged.

In this example, "$NONEXISTENT" is not a valid environment variable, so the path remains unchanged −

import os
path = "$NONEXISTENT/Documents/file.txt"
expanded_path = os.path.expandvars(path)
print(expanded_path)      

Output

The result produced is as shown below −

$NONEXISTENT/Documents/file.txt

Example

In this example, we are expanding multiple environment variables "$HOME" and "$TEMP" in the given path. Both variables are replaced with their respective values −

import os
path = "$HOME/Documents/$TEMP/file.txt"
expanded_path = os.path.expandvars(path)
print(expanded_path)  

Output

We get the output as shown below −

C:\Users\Lenovo/Documents/C:\Users\Lenovo\AppData\Local\Temp/file.txt
os_path_methods.htm
Advertisements