What is a cross-platform way to get the home directory?
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())
How to find the real user home directory using python?
I think os.path.expanduser(path)
could be helpful.
On Unix and Windows, return the argument with an initial component of
~
or~user
replaced by that user‘s home directory.On Unix, an initial
~
is replaced by the environment variable HOME if it is set; otherwise the current user’s home directory is looked up in the password directory through the built-in modulepwd
. An initial~user
is looked up directly in the password directory.On Windows, HOME and USERPROFILE will be used if set, otherwise a combination of HOMEPATH and HOMEDRIVE will be used. An initial
~user
is handled by stripping the last directory component from the created user path derived above.If the expansion fails or if the path does not begin with a tilde, the path is returned unchanged.
So you could just do:
os.path.expanduser('~user')
Where is Python's home directory?
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)
Which for me outputs:
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:
which python
(Unix)where python
(Windows)
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__)
Which for me outputs:
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
Find home directory in Python?
To get the homedir in python, you can use os.path.expanduser('~')
.
This also works if it's part of a longer path, such as os.path.expanduser('~/some/directory/file.txt')
. If there is no ~ in the path, the function will return the path unchanged.
So depending on what you want to do it's better than reading os.environ['HOME']
The username is available through getpass.getuser()
Find the current directory and file's directory
To get the full path to the directory a Python file is contained in, write this in that file:
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
(Note that the incantation above won't work if you've already used os.chdir()
to change your current working directory, since the value of the __file__
constant is relative to the current working directory and is not changed by an os.chdir()
call.)
To get the current working directory use
import os
cwd = os.getcwd()
Documentation references for the modules, constants and functions used above:
- The
os
andos.path
modules. - The
__file__
constant os.path.realpath(path)
(returns "the canonical path of the specified filename, eliminating any symbolic links encountered in the path")os.path.dirname(path)
(returns "the directory name of pathnamepath
")os.getcwd()
(returns "a string representing the current working directory")os.chdir(path)
("change the current working directory topath
")
Find /home/user in python as root user
import os
username = os.getenv("USER")
if(username != 'root'):
print(os.path.expanduser('~'+username))
How do I start the file path from the users directory?
You can use the same ~
across different platforms with os.path.expanduser
.
How to read data from home directory in Python
Using current directory path (assuming that is in the project) and appending the remaining static file path:
import os
current_dir = os.path.abspath(os.getcwd())
path = current_dir + "/RequestJson/request1.json"
with open(path, 'r') as f:
f.write(data)
Related Topics
Plt.Figure.Figure.Show() Does Nothing When Not Executing Interactively
Python Requests Json Returns Single Quote
How to Specify Table for Beautifulsoup to Find
Sharing Psycopg2/Libpq Connections Across Processes
Python Deepcopy and Shallow Copy and Pass Reference
Run Python Script Only If It's Not Running
How to Split My 800X480 5-Inch Screen into 2 Parts
How to Import the Class Within the Same Directory or Sub Directory
Fitting Empirical Distribution to Theoretical Ones With Scipy (Python)
Unresolved Reference Issue in Pycharm
Check If All Elements in a List Are Identical
Selecting With Complex Criteria from Pandas.Dataframe
Find Intersection of Two Nested Lists
Accessing Dict Keys Like an Attribute
Convert Utc Datetime String to Local Datetime
How to Get a Function Name as a String