Python (Scripting) - Users Home Directory

by
Jeremy Canfield |
Updated: April 01 2024
| Python (Scripting) articles
os.path.expanduser can be used to get a users home directory.
#!/usr/bin/python
import os
home = os.path.expanduser('~')
print(home)
Which should return something like this (on a Mac or Linux system).
/home/john.doe
If using Python version 3.4 or high, Path.home() can be used.
#!/usr/bin/python
from pathlib import Path
home = Path.home()
print(home)
Which should return something like this (on a Windows system).
C:\Users\johndoe
Often, Python scripts run on Windows need two backslashes such as C:\\Users\\johndoe. This is kind of weird, but I usually have to go with a single back slash following Path.home when using f format and then double back slashes for any additional directories.
f"{Path.home()}\Downloads\\"
Did you find this article helpful?
If so, consider buying me a coffee over at