Pathing
Default search path
At startup, the Python module search path checks, in this order, for files in:
1) The home directory of the program
2) PYTHONPATH
directories
3) Standard library directories
import sys
sys.path
['',
'C:\\Users\\nhounshell\\Documents\\Projects',
'C:\\Users\\nhounshell\\AppData\\Local\\Continuum\\Anaconda3\\python36.zip',
'C:\\Users\\nhounshell\\AppData\\Local\\Continuum\\Anaconda3\\DLLs',
'C:\\Users\\nhounshell\\AppData\\Local\\Continuum\\Anaconda3\\lib',
'C:\\Users\\nhounshell\\AppData\\Local\\Continuum\\Anaconda3',
'C:\\Users\\nhounshell\\AppData\\Roaming\\Python\\Python36\\site-packages',
'C:\\Users\\nhounshell\\AppData\\Local\\Continuum\\Anaconda3\\lib\\site-packages',
'C:\\Users\\nhounshell\\AppData\\Local\\Continuum\\Anaconda3\\lib\\site-packages\\Babel-2.5.0-py3.6.egg',
'C:\\Users\\nhounshell\\AppData\\Local\\Continuum\\Anaconda3\\lib\\site-packages\\win32',
'C:\\Users\\nhounshell\\AppData\\Local\\Continuum\\Anaconda3\\lib\\site-packages\\win32\\lib',
'C:\\Users\\nhounshell\\AppData\\Local\\Continuum\\Anaconda3\\lib\\site-packages\\Pythonwin',
'C:\\Users\\nhounshell\\AppData\\Local\\Continuum\\Anaconda3\\lib\\site-packages\\IPython\\extensions',
'C:\\Users\\nhounshell\\Documents\\.ipython']
Home directory
If you’re running a top-level file as a program, Home
is that file’s directory location.
If you’re working interactively, it’s whatever directory you’re working in.
Modifying the search path
sys.path
is just a list. As such, you can append things to it.
For instance, an unrelated, nested directory somewhere else in this repository.
sys.path.append('../File IO/data/secret_unrelated_folder')
import surprise
You're a hacker now.
sys.modules['surprise']
<module 'surprise' from '../File IO/data/secret_unrelated_folder\\surprise.py'>
Relative Pathing Tools
Because Python only knows how to look at Home and a couple other things, as a package’s codebase grows, it can get difficult to keep all of your imports straight.
And you can’t always rely on using the handy, Unix '..'
notation to represent relative filepaths.
__file__
and os.getcwd()
These two features can be used to get creative with your pathing.
!type "samplepackage\subdirectory\doublenested.py"
def test_fn():
print("I'm like two levels down.")
import os
getcwdResult = os.getcwd()
fileResult = os.path.dirname(__file__)
from samplepackage.subdirectory.doublenested import getcwdResult, fileResult
os.getcwd()
gives you the absolute filepath of where you’re calling Python
getcwdResult
'C:\\Users\\nhounshell\\Documents\\github\\BlackBook\\Python\\Modules and Packages'
Whereas __file__
strictly returns the filepath of that file’s location, regardless of why Python’s looking at it.
fileResult
'C:\\Users\\nhounshell\\Documents\\github\\BlackBook\\Python\\Modules and Packages\\samplepackage\\subdirectory'