Change language

Python | os.path.expanduser () method

On Unix and Windows, return the argument by replacing the initial ~ or ~ user with the home directory of the given user. On Unix, the initial ~ is replaced by the HOME environment variable, if set; otherwise, the current user’s home directory is looked up in the password directory using the built-in pwd module. The initial ~ user is looked up directly in the password directory. On Windows, USERPROFILE will be used if set, otherwise the combination of HOMEPATH and HOMEDRIVE will be used. The original ~ user is handled by removing the last directory component from the generated user path obtained above. If expansion fails or the path does not start with a tilde, the path is returned unchanged. Changed in version 3.6: Accepts a path-like object. Changed in version 3.8: No longer uses HOME on Windows.
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)

# Python program to explain os.path.expanduser() method
   
# importing os.path module
import os.path
 
 
# Path
path = "~/file.txt"
 
# Expand an initial ~ component
# in the given path
# using os.path.expanduser() method
full_path = os.path.expanduser(path)
 
# print the path after
# expanding the initial ~ component
# in the given path
print(full_path)
 
 
# Change the value of
# HOME environment variable
os.environ["HOME"] = "/home / GeeksForGeeks"
 
 
# Now, Expand the initial ~ component
# in the same path
# using os.path.expanduser() method
full_path = os.path.expanduser(path)
 
# print the path after
# expanding intial ~ component
# in the given path
print(full_path)
 
 
# While expansion, An initial
# ~user component is looked
# up directly in the password directory.
 
# Path having an initial
# ~user component
path = "~ihritik / file.txt"
 
# Expand the initial ~user
# component in the given path
# using os.path.expanduser() method
full_path = os.path.expanduser(path)
 
# print the path after
# expanding the initial ~user
# component in the given 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)

# Python program to explain os.path.expandvars() method
    
# importing os.path module
import os.path
  
# On Windows % name % expansions
# are supported in addition to
# $name and ${name}
  
# Path 1
path1 = R"% HOMEPATH %Directoryfile.txt"
  
# Path 2
path2 = R"C:Users$USERNAMEDirectoryfile.txt"
  
# Path 3
path3 = R"${TEMP}file.txt"
  
# Expand the environment variables
# with their corresponding
# value in the given paths 
exp_var1 = os.path.expandvars(path1)
exp_var2 = os.path.expandvars(path2)
exp_var3 = os.path.expandvars(path3)
  
# Print the given paths with
# environment variables expanded
print(exp_var1)
print(exp_var2)
print(exp_var3)
  
  
# In the above example
# os.path.expandvars() method
# replaced the environment variables
# ’HOMEPATH’, ’USERNAME’ and ’TEMP’
# with their corresponding values

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

# Python program to explain os.path.expandvars() method
    
# importing os.path module
import os.path
  
# If environment variable
# is malformed or does not exists
# then the given path will be
# left unchanged
  
# Path
path = R"${MYHOME}/Directory / file.txt"
  
# Expand the environment variables
# with their corresponding
# value in the given paths 
exp_var = os.path.expandvars(path)
  
# Print the given patha with
# environment variables expanded
print(exp_var)
  
  
# As ’MYHOME’ environment variable
# does not exists so
# os.path.expandvars() method
# will return the given path
# unchanged

Output:

${MYHOME}/Directory/file.txt

More on OS.PATH methods

os.path.abspath (path) - Returns the normalized absolute path.

os.path.basename (path) The base name of the path (equivalent to

os.path.split ( (path) [1]).

os.path.commonprefix (list) - Returns the longest prefix of all paths in the list.

os.path.dirname (path) - Returns the name of the path directory path.

os.path.exists (path) - Returns True if path points to an existing path or handle to an open file.

os.path.expanduser (path) - Replaces ~ or ~ user with the user’s home directory.

os.path.expandvars (path) - returns an argument with substituted environment variables ($ name or $ {name} is replaced by the environment variable name). Does not replace non-existent names. Also replaces% name% on Windows.

os.path.getatime (path) - time of the last access to the file, in seconds.

os.path.getmtime (path) - the time the file was last modified, in seconds.

os.path.getctime (path) - file creation time (Windows), file last modification time (Unix).

os.path.getsize (path) - file size in bytes.

os.path.isabs (path) - whether the path is absolute.

os.path.isfile (path) - whether the path is a file.

os.path.isdir (path) - is the path a directory.

os.path.islink (path) - whether the path is a symbolic link.

os.path.ismount (path) - Whether the path is a mount point.

os.path.join ( (path1 [, path2 [, ...]]) - connects paths, taking into account the peculiarities of the operating system.

os.path.normcase (path) - normalizes the case of the path (on file systems that are not case sensitive, converts the path to lower case).

os.path.normpath (path) - normalizes the path, removing redundant delimiters and links to previous directories. On Windows, converts forward slashes to backslashes.

os.path.realpath (path) - Returns the canonical path, removing all symbolic links (if supported).

os.path.relpath (path, start = None) - calculates the path relative to the start directory (by default, relative to the current directory).

os.path.samefile (path1, path2) - Whether path1 and path2 point to the same file or directory.

os.path.sameopenfile (fp1, fp2) - Whether the descriptors fp1 and fp2 point to the same open file.

os.path.split ( (path) - splits the path into a tuple (head, tail), where the tail is the last component of the path, and the head is everything else. The tail never starts with a slash (if the path ends with a slash, then the tail is empty). If there are no slashes in the path, then the head will be empty.

os.path.split (drive (path) - splits the path into pairs (drive, tail).

os.path.split (ext (path) - splits the path into a pair (root, ext), where ext starts with a dot and contains at most one dot.

os.path.supports_unicode_filenames - Whether the file system supports Unicode.

Archived version

The

os.path.expanduser() method in Python is used to expand the original path of a component ~ (tilde character) or ~ user in the given path to the user "s home directory.

On Unix platforms, the leading character ~ is replaced by the value of the environment variable HOME if installed. Otherwise, os.path.expanduser() search method for user ’s home directory in the password directory using the built-in PWD module. The path containing the original custom component is looked up directly in the password directory.

On Windows platform, the initial character ~ is replaced by the value of the HOME environment variable and USERPROFILE if set. Otherwise, HOMEPATH and HOMEDRIVE environment variable will be used. Whereas the path containing the initial ~ user component is processed by replacing the last directory component with the ~ user from the above path.

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: Using the os.path.expanduser () method (on Unix)

# Python program to explain the method os.path.expanduser ()

 
# import of the os.path module

import os.path

 

 
# Path

path = "~ / file.txt"  

 
# Expand initial ~ component
# in the specified path
# using the os.path.expanduser () method

full_path = os.path.expanduser (path)

 
# print path after
# starting component extension
# in the specified path

print ( full_path)

 

 
# Change value
# HOME environment variable

os.environ [ "HOME" ] = " / home / GeeksForGeeks "

 

 
# Now expand the initial component ~
# in the same path
# using the os.path.expanduser () method

full_path = os.path.expanduser (path)

 
# print path after
# extending the initial ~ component
# in the specified path

print (full_path)

 

 
# While extension, initial # ~ the custom component is being viewed
# directly in the password directory.

 
# A path that has an initial
# ~ custom component

path = "~ ihritik / file. txt "

  
# Expand initial ~ user
# component in the specified path
# using the os.path.expanduser () method

full_path = os.path.expanduser (path)

 
# print path after
# extension of initial ~ user viewer
# component in the specified path

print (full_path)

Output:

 /home/ihritik/file.txt /home/GeeksForGeeks/file.txt /home/ihritik/file.txt 

Code # 2: Using the os. path.expanduser () (on Windows)

Exit :

  Users  Hritik  Directory  file.txt C:  Users  Hritik  Directory  file.txt C:  Users  Hritik  AppData  Local  Temp  file.txt 

Code # 3: 3: If the environment variable does not exist

# Python program to explain the os.path.expandvars () method

 
# import of the os.path module

import os.path

  
# On Windows% name% extensions
# are supported in addition to
# $ name and $ {name}

 
# Path 1

path1 = R "% HOMEPATH% Directoryfile.txt "

  
# Path 2

path2 = R "C: Users $ USERNAMEDirectoryfile.txt"

 
# Path 3

path3 = R "$ {TEMP} file.txt"

 
# Expand the environment variables
# with their respective
# the value in the specified paths  

exp_var1 = os.path.expandvars (path1)

exp_var2 = os.path.expandvars ( path2)

exp_var3 = os.path .expandvars (path3)

 
# Output path data using
# extended environment variables

print ( exp_var1)

print (exp_var2)

print (exp_var3)

 

 
# In the above example
# os.path .expandvars () method
# replaced environment variables
# & # 39; HOMEPATH & # 39; , & # 39; USERNAME & # 39; and & # 39; TEMP & # 39;
# with appropriate values ​​

# Python program to explain the os.path.expandvars () method

 
# import of the os.path module

import os.path

 
# If the environment variable
# corrupted or does not exist
# then the given path will be
# left unchanged

  
# Path

path = R " $ {MYHOME} / Directory / file.txt "

  
# Expand the environment variables
# with their respective
# the value in the specified paths

exp_var = os.path.expandvars (path)

 
# Print this patch with
# extended environment variables

print (exp_var)

 

 
# Like environment variable & # 39; MYHOME & # 39;
# doesn’t exist like that
# os.path.expandvars () method
# will return the specified path
# no change

Output:

 $ {MYHOME} /Directory/file.txt 

Link: https://docs.python.org/3/library/os.path.html

Shop

Gifts for programmers

Best laptop for Excel

$
Gifts for programmers

Best laptop for Solidworks

$399+
Gifts for programmers

Best laptop for Roblox

$399+
Gifts for programmers

Best laptop for development

$499+
Gifts for programmers

Best laptop for Cricut Maker

$299+
Gifts for programmers

Best laptop for hacking

$890
Gifts for programmers

Best laptop for Machine Learning

$699+
Gifts for programmers

Raspberry Pi robot kit

$150

Latest questions

PythonStackOverflow

Common xlabel/ylabel for matplotlib subplots

1947 answers

PythonStackOverflow

Check if one list is a subset of another in Python

1173 answers

PythonStackOverflow

How to specify multiple return types using type-hints

1002 answers

PythonStackOverflow

Printing words vertically in Python

909 answers

PythonStackOverflow

Python Extract words from a given string

798 answers

PythonStackOverflow

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

606 answers

PythonStackOverflow

Python os.path.join () method

384 answers

PythonStackOverflow

Flake8: Ignore specific warning for entire file

360 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

How to specify multiple return types using type-hints

Printing words vertically in Python

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically