Python | os.path.expandvars() method
Last Updated :
10 Nov, 2021
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. os.path the module is a submodule of OS module in Python used for common pathname manipulation.
os.path.expandvars()
method in Python is used to expand the environment variables in the given path. It replaces substrings of the form $name or ${name} in the given path with the value of environment variable name.
If the given path contains malformed environment variable names or environment variables that do not exist then os.path.expandvars()
method will left it unchanged.
On Windows, %name% expansion is also supported in addition to $name and ${name}expansion.
Syntax: os.path.expandvars(path)
Parameter:
path: A path-like object representing a file system path. A path-like object is either a string or bytes object representing a path.
Return Type: This method returns a string which represents the parameter with environment variables expanded.
Code #1: Use of os.path.expandvars() method
import os.path
path = "$HOME/file.txt"
exp_var = os.path.expandvars(path)
print (exp_var)
os.environ[ "HOME" ] = "/home/GeeksForGeeks"
path = "$HOME/Documents/file.txt"
exp_var = os.path.expandvars(path)
print (exp_var)
os.environ[ "USER" ] = "ihritik"
path = "/home/${USER}/file.txt"
exp_var = os.path.expandvars(path)
print (exp_var)
|
Output:
/home/ihritik/file.txt
/home/GeeksForGeeks/Documents/file.txt
/home/ihritik/file.txt
Code #2: Use of os.path.expandvars() method (On Windows)
import os.path
path1 = R "% HOMEPATH %\Directory\file.txt"
path2 = R "C:\Users\$USERNAME\Directory\file.txt"
path3 = R "${TEMP}\file.txt"
exp_var1 = os.path.expandvars(path1)
exp_var2 = os.path.expandvars(path2)
exp_var3 = os.path.expandvars(path3)
print (exp_var1)
print (exp_var2)
print (exp_var3)
|
Output:
\\Users\\Hritik\\\Directory\\file.txt
C:\\Users\\Hritik\\\Directory\\file.txt
C:\\Users\\Hritik\\AppData\\Local\\Temp\\file.txt
Code #3: If environment variable does not exists
import os.path
path = R "${MYHOME}/Directory/file.txt"
exp_var = os.path.expandvars(path)
print (exp_var)
|
Output:
${MYHOME}/Directory/file.txt
Reference: https://docs.python.org/3/library/os.path.html
Share your thoughts in the comments
Please Login to comment...