The Python Oracle

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

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Life in a Drop

--

Chapters
00:00 What Is A Cross-Platform Way To Get The Home Directory?
00:22 Accepted Answer Score 2106
00:52 Answer 2 Score 37
01:03 Answer 3 Score 23
01:37 Answer 4 Score 5
01:54 Thank you

--

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

--

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())