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.
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)
/home/ihritik/file.txt /home/GeeksForGeeks/file.txt /home/ihritik/file.txt
Code #2: Use of os.path.expanduser() method (On Windows)
\\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
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.