The os module in the standard library includes the path sub-module which provides useful functions for working with and manipulating pathnames.

The expandvars() function in the path sub-module is used to expand environment variables contained in a pathname to their actual values.

Environment variables are useful for easily storing and accessing important information. You can set an environment variable using the dictionary-like object called  os.environ.

import os
os.environ["NAME"] = "John"

print(os.environ["NAME"])

To use the expandvars() function, we will first need to import it in our program as shown below.

from os.path import expandvars
expandvars(p)
p The pathname containing the variables to be expanded.

The function replaces all the environment variables with the actual values. Typically, the variables to be expanded are usually preceded by a dollar sign($). 

The function does not validate whether the resulting path exists or not, it works on mere strings.

import os
from os.path import expandvars

#set some environment variables
os.environ["USER"] = "john"
os.environ["PROJECTDIR"] = "pynerds"

p = r"C:\users\$USER\desktop\$PROJECTDIR\tests.py"
expanded = expandvars(p)

print(expanded)

C:\users\john\desktop\pynerds\tests.py

In the above example, we have defined two environment variables, "USER" and "PROJECTDIR", using them preceded by a dollar sign in a path, automatically marks them as variables to be replaced.

If a variable that has not been set is used in the path, the expandvars() function will simply return it as is i.e without any replacement and without raising any errors.

import os
from os.path import expandvars


os.environ["USER"] = "john"
os.environ["PROJECTDIR"] = "pynerds"


#the path variable is not set
path = r"\$USER\desktop\$HOME\$PROJECTDIR\tests.py"
expanded = expandvars(path)
print(expanded)

\john\desktop\$HOME\pynerds\tests.py

As you can see above, the $HOME variable is left as it was because it has not been set as an environment variable.