The Python Oracle

What is a cross-platform way to get the home directory?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Secret Catacombs

--

Chapters
00:00 Question
00:30 Accepted answer (Score 2008)
00:56 Answer 2 (Score 31)
01:10 Answer 3 (Score 16)
01:55 Answer 4 (Score 2)
02:18 Thank you

--

Full question
https://stackoverflow.com/questions/4028...

Accepted answer links:
[os.path.expanduser]: http://docs.python.org/library/os.path.h...
[pathlib.Path.home()]: https://docs.python.org/3/library/pathli...

Answer 4 links:
[pathlib]: https://docs.python.org/3/library/pathli...
[Path.expanduser()]: https://docs.python.org/3/library/pathli...
[Path.home()]: https://docs.python.org/3/library/pathli...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #crossplatform #homedirectory

#avk47



ACCEPTED ANSWER

Score 2113


You want to use os.path.expanduser.
This will ensure it works on all platforms:

from os.path import expanduser
home = expanduser("~")

If you're on Python 3.5+ you can use pathlib.Path.home():

from pathlib import Path
home = str(Path.home())

But it's usually better not to convert Path.home() to string. It's more natural to use this way:

with open(Path.home() / ".ssh" / "known_hosts") as f:
    lines = f.readlines()



ANSWER 2

Score 37


I found that pathlib module also supports this.

from pathlib import Path
>>> Path.home()
WindowsPath('C:/Users/XXX')



ANSWER 3

Score 23


I know this is an old thread, but I recently needed this for a large scale project (Python 3.8). It had to work on any mainstream OS, so therefore I went with the solution @Max wrote in the comments.

Code:

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

Output Windows:

PS C:\Python> & C:/Python38/python.exe c:/Python/test.py
C:\Users\mXXXXX

Output Linux (Ubuntu):

rxxx@xx:/mnt/c/Python$ python3 test.py
/home/rxxx

I also tested it on Python 2.7.17 and that works too.




ANSWER 4

Score 5


This can be done using pathlib, which is part of the standard library, and treats paths as objects with methods, instead of strings.

from pathlib import Path

home: str = str(Path('~').expanduser())