The os
module in the standard library includes the path submodule which offers a variety of useful functions for manipulating and examining file paths.
The expanduser()
function in the path
module expands the tilde character (~
) at the beginning of a path string to the home directory of the current user. This can be useful when constructing absolute paths to user-specific locations, such as the user’s home folder, desktop, documents folder, etc.
For example if you have a file named "myfile.txt" in the users desktop, you can specify the path as "~/desktop/myfile.txt", then pass the string to the expanduser()
function to get the absolute path of the file.
expanduser(path)
path |
A string containing the path to be expanded. |
The function simply replaces a tilde character at the beginning of the path
with the current user's home directory. It does not do any verification to check whether the path is valid or not.
from os.path import expanduser
mypath = r'~\desktop\myfile.txt'
absolute = expanduser(mypath)
print(absolute)
C:\Users\John\desktop\myfile.txt
In the above example, the path to be expanded is "~\desktop\myfile.txt"
we passed the path to the expanduser()
function. The resulting string have the tilde character replaced with the home directory of the user which is "C:\Users\John". As earlier mentioned, the function works with mere strings and does not verify whether the resulting path exists or not.
If the tilde character is not at the beginning of the path string, the expanduser()
function return the string as-is, without making any changes.
If the tilde character is not followed by the os.sep
character( backslash on windows, forward slash on Unix systems), the expanduser()
function will assume that the first part of the path(before the first os.sep
character) represents a username and will therefore simply add the base path to all users in front of the path string.
from os.path import expanduser
mypath = r"~james\desktop\myfile.txt"
absolute = expanduser(mypath)
print(absolute)
C:\Users\james\desktop\myfile.txt