- Getting Home Directory with pathlib
- 5 Answers 5
- EDIT
- How to find the real user home directory using Python?
- Using os module
- Example — Home Directory Path
- Output
- Example — File Inside Home Directory
- Output
- Example — ~ Substitution
- Output
- Using pathlib module
- Example — Home Directory Path
- Output
- Example — File Inside Home Directory
- Output
- Example — ~ Substitution
- Output
- Where is Python’s home directory?
- 1 Answer 1
- What is a cross-platform way to get the home directory?
- 5 Answers 5
Getting Home Directory with pathlib
Looking through the new pathlib module in Python 3.4, I notice that there isn’t any simple way to get the user’s home directory. The only way I can come up with for getting a user’s home directory is to use the older os.path lib like so:
import pathlib from os import path p = pathlib.Path(path.expanduser("~"))
5 Answers 5
As of python-3.5, there is pathlib.Path.home() , which improves the situation somewhat.
>>>pathlib.Path.home() WindowsPath('C:/Users/username')
>>>pathlib.Path.home() PosixPath('/home/username')
@user9074332 — how about Path(‘~username’).expanduser() ? There’s also os.path.expanduser(‘~username’) , but pay close attention to how each of these fails if the user does not exist!
p = PosixPath('~/films/Monty Python') p.expanduser() # => PosixPath('/home/eric/films/Monty Python')
It seems that this method was brought up in a bug report here. Some code was written (given here) but unfortunately it doesn’t seem that it made it into the final Python 3.4 release.
Incidentally the code that was proposed was extremely similar to the code you have in your question:
# As a method of a Path object def expanduser(self): """ Return a new path with expanded ~ and ~user constructs (as returned by os.path.expanduser) """ return self.__class__(os.path.expanduser(str(self)))
EDIT
Here is a rudimentary subclassed version PathTest which subclasses WindowsPath (I’m on a Windows box but you could replace it with PosixPath ). It adds a classmethod based on the code that was submitted in the bug report.
from pathlib import WindowsPath import os.path class PathTest(WindowsPath): def __new__(cls, *args, **kwargs): return super(PathTest, cls).__new__(cls, *args, **kwargs) @classmethod def expanduser(cls): """ Return a new path with expanded ~ and ~user constructs (as returned by os.path.expanduser) """ return cls(os.path.expanduser('~')) p = PathTest('C:/') print(p) # 'C:/' q = PathTest.expanduser() print(q) # C:\Users\Username
How to find the real user home directory using Python?
On a multiuser operating system, a home directory is a file system location that holds the files specific to a particular user.
A login directory is another name for a home directory.You may obtain the home directory using Python in a number of ways.
Using os module
The os.path.expanduser() function in Python provides the most straightforward method for retrieving the user home directory across all platforms. The Python os module offers os.path.expanduser(«) to retrieve the home directory. This also functions if it is a part of a longer path. The function will return the path unchanged if there is no ~ in the path.
Example — Home Directory Path
Following is an example to find the home directory using os.path.expanduser() function −
import os home_directory = os.path.expanduser( '~' ) print( home_directory )
Output
Following is an output of the above code −
Example — File Inside Home Directory
Use os.path.join to create the path C:\Users\Lenovo\Downloads\Works −
import os home_directory = os.path.expanduser( '~' ) path = os.path.join( home_directory, 'Documents', 'mysql_access' ) print( path )
Output
Following is an output of the above code −
C:\Users\Lenovo\Documents\mysql_access
Example — ~ Substitution
If you already have a string path, such as C:\Users\Lenovo\Downloads\Works, where you wish to replace with the home directory path, you can put it in directly to.expanduser() instead of using the safe way to generate paths, which is os.path.join() −
import os path = os.path.expanduser('~\Documents\mysql_access') print( path )
Output
Following is an output of the above code −
C:\Users\Lenovo\Documents\mysql_accessy
Using pathlib module
The pathlib module in Python can also be used to obtain the user’s home directory.
Example — Home Directory Path
Following is an example to find the home directory path.home() function −
from pathlib import Path home_directory = Path.home() print( f'Path: home_directory> !' )
Output
Following is an output of the above code −
Example — File Inside Home Directory
Using.joinpath, you can also quickly create paths inside the user’s home directory () −
from pathlib import Path path = Path.home().joinpath( 'Documents', 'mysql_access' ) print(path)
Output
Following is an output of the above code −
C:\Users\Lenovo\Documents\mysql_access
Example — ~ Substitution
Use.expanduser() if you already have a string path, such as /Documents/mysql_access, where you want to replace with the path to your home directory −
from pathlib import Path path_string = '~\Documents\mysql_access' path = Path(path_string).expanduser() print(path)
Output
Following is an output of the above code −
C:\Users\Lenovo\Documents\mysql_access
Where is Python’s home directory?
I have Python 2.7 installed, Im looking at trying tensorflow and for windows it looks like it only works on python 3.5, I downloaded the python installer and it is apparently installed, but where? Python 2.7 has a Python27 directory in C:, but I cant locate 3.5 anywhere. I tried the installer again and it asked if I wanted to repair or remove. EDIT: Im really trying to find pip3, which I assume is in the python35/scripts directory
You don’t really need to know the path if you have the Python Installer. It is installed in C:\Windows which is already in the path, and py -2.7 -m pip
1 Answer 1
Where is Python installed? or where is Python’s HOME directory?
An easy way to find where Python is installed, would be to do:
import sys print(sys.executable)
C:\Users\Vallentin\AppData\Local\Programs\Python\Python36-32\python.exe
You can also use sys.exec_prefix which would be the equivalent of os.path.dirname(sys.executable) .
If you then copy the directory part and paste it into Windows Explorer. Then it would take you to Python’s home directory. You are then correct that pip would be located at.
C:\Users\Vallentin\AppData\Local\Programs\Python\Python36-32\Scripts\pip3.exe
From a command line this can also be done in a single line:
python -c "import sys; print(sys.executable)"
Alternatively you can also do:
Where is a Python module installed?
If you want to find where a Python module is located, then like print(__file__) the same can be done with modules:
import re import flask print(re.__file__) print(flask.__file__)
C:\Users\Vallentin\AppData\Local\Programs\Python\Python36-32\lib\re.py C:\Users\Vallentin\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask-0.12-py3.6.egg\flask\__init__.py
What is a cross-platform way to get the home directory?
I need to get the location of the home directory of the current logged-on user. Currently, I’ve been using the following on Linux:
This is marked a duplicate of How to find the real user home directory using python, but I voted to reopen because this answer works on Python 3 and the older answer does not.
5 Answers 5
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()
it should be noted that if the user is logged on to a domain on windows and has their profile home folder set in active directory then this will report that mapped network folder instead of the local home directory
I wonder why nobody else mentioned it in this question, but if you need to know where another user’s home directory is you can use os.path.expanduser(‘~username’) . Probably applies only for Linux though.
The result is the same. If you generally are working with pathlib, you may prefer the pathlib solution (and omit the call of str ). If you just want the path as string, they both do the same.
@dcolish please remove str() from the answer. It’s so much more natural to build a path with the slash / such as `Path.home() / «location_of_a_file.txt».
I found that pathlib module also supports this.
from pathlib import Path >>> Path.home() WindowsPath('C:/Users/XXX')
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.
import os print(os.path.expanduser("~"))
PS C:\Python> & C:/Python38/python.exe c:/Python/test.py C:\Users\mXXXXX
rxxx@xx:/mnt/c/Python$ python3 test.py /home/rxxx
I also tested it on Python 2.7.17 and that works too.
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())
This doesn’t really qualify for the question (it being tagged as cross-platform ), but perhaps this could be useful for someone.
How to get the home directory for effective user (Linux specific).
Let’s imagine that you are writing an installer script or some other solution that requires you to perform certain actions under certain local users. You would most likely accomplish this in your installer script by changing the effective user, but os.path.expanduser(«~») will still return /root .
The argument needs to have the desired user name:
Note that the above works fine without changing EUID, but if the scenario previously described would apply, the example below shows how this could be used:
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 else: self.gid = grp.getgrnam(group).gr_gid def __enter__(self): self.original_uid = os.getuid() self.original_gid = os.getgid() os.setegid(self.uid) os.seteuid(self.gid) def __exit__(self, type, value, traceback): os.seteuid(self.original_uid) os.setegid(self.original_gid) if __name__ == '__main__': with Identity("hedy", "lamarr"): homedir = os.path.expanduser(f"~/") with open(os.path.join(homedir, "install.log"), "w") as file: file.write("Your home directory contents have been altered")