pathlib
(Python 3.5 and up)On Python 3.5 and higher, you can get the path of the user's operating system (OS) home directory by using the built-in pathlib
library:
1 2 3 4 5 | from pathlib import Path home_dir = Path.home() print( f'Path: { home_dir } !' ) |
In the code above, home_dir
is an object of class PosixPath
(if you're running on Linux or macOS) or WindowsPath
(if you're running on Windows). You can print
it directly (including inside formatted f-strings as in the example above), but if you want to perform string operations on it, you must first convert it to a string:
1 2 3 4 | from pathlib import Path home_dir = Path.home() home_dir_str = str( home_dir ) |
You can also easily build paths inside the user's home directory using .joinpath()
. For example, to build a path representing ~/Documents/myfile.txt
(a file named myfile.txt
inside the Documents
subdirectory in the user's home directory):
1 2 3 4 5 | from pathlib import Path filepath = Path.home().joinpath( 'Documents', 'myfile.txt' ) print( filepath ) |
~
SubstitutionIf you already have a string path like ~/Documents/myfile.txt
where you want to replace ~
with the home directory path, you can use .expanduser()
:
1 2 3 4 5 6 | from pathlib import Path filepath_str = '~/Documents/myfile.txt' filepath = Path( filepath_str ).expanduser() print( filepath ) |
os.path.expanduser
An alternative to pathlib
that is available on all Python 3 versions is the built-in os.path
library. You can use os.path.expanduser
to get the home directory of the current user:
1 2 3 4 5 | import os home_dir = os.path.expanduser( '~' ) print( home_dir ) |
To build the path ~/Documents/myfile.txt
, you can use os.path.join
:
1 2 3 4 5 6 | import os home_dir = os.path.expanduser( '~' ) filepath = os.path.join( home_dir, 'Documents', 'myfile.txt' ) print( filepath ) |
~
SubstitutionThe safe way to build paths is using os.path.join()
, but if you already have a string path like ~/Documents/myfile.txt
where you want to replace ~
with the home directory path, you can just pass it in directly to .expanduser()
:
1 2 3 4 5 | import os filepath = os.path.expanduser( '~/Documents/myfile.txt' ) print( filepath ) |
On Windows, the above code outputs C:\Users\jlee/Documents/myfile.txt
, where the slashes are not uniform (i.e., incorrect). To avoid this problem (i.e., for portable code), you should use os.path.join
, which automatically chooses the correct file path slashes for the system you're currently using.