Coder Perfect

What is the best approach to access the home directory in Python across platforms?


I need to know where the current logged-on user’s home directory is located. On Linux, I’m now using the following:


On Windows, however, this does not function. What is the best method to achieve this across platforms?

Asked by Nathan Osman

Solution #1

os.path.expanduser is what you want to utilise. This ensures that it works across all platforms:

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

You can use pathlib.Path.home() if you’re using Python 3.5+:

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

Answered by dcolish

Solution #2

This is also supported by the pathlib module, which I discovered.

from pathlib import Path
>>> Path.home()

Answered by Jaeyoon Jeong

Solution #3

I realize this is an old thread, but I recently required this information for a large-scale project (Python 3.8). Because it has to work on any mainstream OS, I opted with the method suggested by @Max in the comments.


import os

Output Windows:

PS C:\Python> & C:/Python38/python.exe c:/Python/

Output Linux (Ubuntu):

rxxx@xx:/mnt/c/Python$ python3

I also tested it on Python 2.7.17, and it works there as well.

Answered by user56700

Solution #4

Although this doesn’t really fit the query (it’s categorized as cross-platform), it might be beneficial to someone.

What is the best way to acquire the home directory for a productive user? (Linux specific).

Assume you’re building an installer script or another solution that necessitates you doing certain operations under the control of specific local users. Changing the effective user in your installer script is the most likely way to do it, although os.path.expanduser(“”) will still return /root.

The desired user name must be included in the argument:


Note that the above works great without changing EUID, however if the scenario stated above applies, the following example explains how to use it:

import os
import pwd
import grp

class Identity():

    def __init__(self, user: str, group: str = None):
        self.uid = pwd.getpwnam(user).pw_uid
        if not group:
            self.gid = pwd.getpwnam(user).pw_gid
            self.gid = grp.getgrnam(group).gr_gid

    def __enter__(self):
        self.original_uid = os.getuid()
        self.original_gid = os.getgid()

    def __exit__(self, type, value, traceback):

if __name__ == '__main__':

    with Identity("hedy", "lamarr"):
        homedir = os.path.expanduser(f"~{pwd.getpwuid(os.geteuid())[0]}/")
        with open(os.path.join(homedir, "install.log"), "w") as file:
            file.write("Your home directory contents have been altered")

Answered by Tammi

Post is based on