Python | os.path.expanduser() method
Last Updated :
11 Oct, 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 module is sub module of OS module in Python used for common pathname manipulation.
os.path.expanduser() method in Python is used to expand an initial path component ~( tilde symbol) or ~user in the given path to user’s home directory.
On Unix platforms, an initial ~ is replaced by the value of HOME environment variable, if it is set. Otherwise, os.path.expanduser() method search for user’s home directory in password directory using an in-built module pwd. Path containing an initial ~user component is looked up directly in the password directory.
On Windows platform, an initial ~ is replaced by the value of HOME and USERPROFILE environment variable, if it is set. Otherwise, HOMEPATH and HOMEDRIVE environment variable will be used. While Path containing an initial ~user component is handled by replacing the last directory component with ~user from the path derived above.
Syntax: os.path.expanduser(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 value which represents the path after expanding an initial path component ~ or ~user in the given path.
Code #1: Use of os.path.expanduser() method (On Unix)
Python3
import os.path
path = "~/file.txt"
full_path = os.path.expanduser(path)
print (full_path)
os.environ[ "HOME" ] = "/home / GeeksForGeeks"
full_path = os.path.expanduser(path)
print (full_path)
path = "~ihritik / file.txt"
full_path = os.path.expanduser(path)
print (full_path)
|
Output:
/home/ihritik/file.txt
/home/GeeksForGeeks/file.txt
/home/ihritik/file.txt
Code #2: Use of os.path.expanduser() method (On Windows)
Python3
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: 3: If environment variable does not exists
Python3
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...