Python Get Home Directory

Learn how to get the current user's home directory in Python using pathlib Path.home(), os.path.expanduser('~'), and environment variables like HOME and USERPROFILE.

Published

Updated

Read time 5 min read

Reviewed byDeepak Prasad

Python Get Home Directory

When you need the current user’s home directory in Python, start with pathlib.Path.home(). It is the clearest, cross-platform API in modern code. If you are already using os.path style paths, os.path.expanduser("~") stays the usual companion. Environment variables such as HOME (Unix) and USERPROFILE (Windows) are fallbacks for integration with shells and tools—know the platform differences before you rely on them alone.

The pathlib documentation describes it as an object-oriented way to work with filesystem paths; Path.home() returns a new path object representing the user’s home directory. For how shells expose HOME on Linux, see where to set environment variables in Linux.

Tested on: Python 3.13.3; kernel 6.14.0-37-generic.


Best way to get home directory in Python

Use pathlib.Path.home() for new code. It resolves the same conceptual location as os.path.expanduser("~") on typical setups, but you get a Path you can join with / without hand-building separators. Use os.path.expanduser("~") when you are extending older scripts that already think in strings.

python
from pathlib import Path
import os.path

print(Path.home())
print(os.path.expanduser("~"))
Output

On this machine both lines print the same absolute path (for example /home/yourname). They can differ in unusual configurations, so treat Path.home() as the primary API and fall back to environment logic only when you must match an external tool exactly.


Get home directory using pathlib Path.home()

Import Path and call home() with no arguments:

python
from pathlib import Path

home = Path.home()
print(home)
Output

You should see one line with your home directory path. No tilde is required; the method asks the operating system for the current user’s profile root.


Convert Path.home() to string

APIs that still expect str (some C extensions, CSV paths, older libraries) need an explicit conversion:

python
from pathlib import Path

home_str = str(Path.home())
print(type(home_str), home_str)
Output

The first token in the output should read <class 'str'>.


Join home directory with a file or folder path

Use the / operator on Path objects instead of concatenating "\\" or "/" by hand—Windows accepts Path’s normalized form when you pass it back to the OS.

python
from pathlib import Path

cfg = Path.home() / ".config" / "myapp" / "settings.toml"
print(cfg)
Output

You should see a single path starting at your home and ending with settings.toml. Create missing parents under ~/.config with create nested directories before the first write to file call.


Get home directory using os.path.expanduser()

expanduser understands ~ for the current user and ~otheruser on POSIX systems when the underlying OS can resolve it:

python
import os.path

print(os.path.expanduser("~"))
Output

Output matches your home path string. This is the idiomatic string-based option next to Path.home().


Get home directory using environment variables

Sometimes you read HOME or USERPROFILE to align with a parent process or a shell script. Prefer os.environ.get("KEY") so a missing variable does not raise KeyError:

python
import os

print(os.environ.get("HOME") or os.environ.get("USERPROFILE"))
Output

On Linux or macOS you normally see HOME; on Windows USERPROFILE carries the profile directory when HOME is absent. When both could apply, Path.home() still tends to be the least surprising API from Python.


HOME vs USERPROFILE on Linux, macOS, and Windows

Platform Common home variable
Linux HOME
macOS HOME
Windows USERPROFILE (often HOMEDRIVE + HOMEPATH)
Cross-platform Python Path.home()

On Windows, do not assume HOME exists unless your runtime or shell sets it; USERPROFILE is the conventional profile root. Python’s own resolution logic for Path.home() follows the platform rules so you do not have to branch manually in most apps.


Get another user’s home directory

  • POSIX: Path(f"/home/{username}") or Path(f"/Users/{username}") on macOS works only if your layout matches; os.path.expanduser(f"~{username}") asks the OS to expand that account’s home when permitted.
  • Windows: profile directories live under C:\Users\<name> by convention, but the real location can be redirected; use OS profiles APIs or configuration data instead of hardcoding drive letters.
  • Permissions: you can compute another user’s path without being allowed to read it; handle PermissionError when you open files.

When in doubt, prefer configuration (explicit base path) over guessing another user’s tree.


Common mistakes when getting home directory in Python

  • Using a literal "~/Documents" path without calling expanduser or building from Path.home()—the tilde stays literal and breaks file opens.
  • Concatenating "\\" or "/" between segments—easy to get wrong on mixed platforms; use Path joins or os.path.join.
  • Reading only HOME on Windows and getting None, then assuming there is no home directory.
  • Dumping os.environ during debugging and pasting huge secrets into logs—stick to the keys you need.
  • Treating Path.home() as a string and passing it to APIs that strictly require str without conversion.
  • Running scripts with sudo and wondering why Path.home() points at /root—you are root now; drop privileges or model the target user explicitly.
  • Hardcoding /home/you or C:\Users\you—breaks other machines, renamed profiles, and relocated home directories.

Python get home directory quick reference table

Approach Example Returns
pathlib (preferred) Path.home() Path
String tilde expansion os.path.expanduser("~") str
Unix-style env os.environ.get("HOME") str or None
Windows-style env os.environ.get("USERPROFILE") str or None
Join under home Path.home() / "subdir" / "file.txt" Path

Summary

Reach for pathlib.Path.home() when you want a modern, object-oriented home path and clean joining with /. Pair it with str(...) when an API still demands strings. Keep os.path.expanduser("~") in mind for legacy os.path code, and treat HOME / USERPROFILE as environment-level hints—especially on Windows where HOME may be missing. Avoid raw string concatenation, bare tildes, and hardcoded profile paths; expect sudo to change whose home you see.


References


Frequently Asked Questions

1. Does Path.home() return a string?

No—it returns a pathlib.Path object; wrap with str() or use str(Path.home() / subpath) when you need plain text for legacy APIs.

2. Why does my script print /root after I use sudo?

The effective user becomes root, so Path.home() and expanduser follow that account; run without elevated privileges or derive the target user explicitly if you need another home.

3. Is HOME reliable on Windows?

Prefer Path.home() cross-platform; on Windows USERPROFILE is the usual profile root while HOME may be unset unless a shell or tool defines it.

4. Can I use a bare tilde string as a path?

A literal tilde in a string is not expanded automatically; use os.path.expanduser or pathlib operations that resolve home for you.
Bashir Alam

Data Analyst and Machine Learning Engineer

Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in OCR, text extraction, data preprocessing, and …