Using hard-coded paths can make code difficult to maintain since it will not be portable. This is especially true in server-side web development. To avoid hard-coded paths, dynamic paths should be used. Here is an example of how to use them effectively, across different modules.
The directory tree for the example is as follows:
The .py files and their locations, along with the variables contained within each and what they print to the standard output, demonstrates how to use dynamic paths. Store these in the locations shown in the diagram and run using “python locate.py”
locate.py
import os import deeper_directory.py_mod_1 as py_mod_1 import deeper_directory.deepest_directory.py_mod_2 as py_mod_2 from deeper_directory import * from deeper_directory.deepest_directory import * print LOCATE_PY_FILENAME = __file__ LOCATE_PY_DIRECTORY_PATH = os.path.abspath(os.path.dirname(__file__)) LOCATE_PY_PARENT_DIR = os.path.abspath(os.path.join(LOCATE_PY_DIRECTORY_PATH, "..")) print "Filename of locate.py: " + LOCATE_PY_FILENAME print "Filepath of locate.py: " + os.path.join(LOCATE_PY_DIRECTORY_PATH, LOCATE_PY_FILENAME) print "Directory Path of locate.py: " + LOCATE_PY_DIRECTORY_PATH print "Parent Directory Path of locate.py: " + LOCATE_PY_PARENT_DIR print print "Filename of py_mod_1.py: " + py_mod_1.PY_MOD_1_PY_FILENAME print "Filepath of py_mod_1.py: " + os.path.join(py_mod_1.PY_MOD_1_PY_DIRECTORY_PATH, py_mod_1.PY_MOD_1_PY_FILENAME) print "Directory Path of py_mod_1.py: " + py_mod_1.PY_MOD_1_PY_DIRECTORY_PATH print "Parent Directory Path of py_mod_1.py: " + py_mod_1.PY_MOD_1_PY_PARENT_DIR print print "Filename of py_mod_2.py: " + py_mod_2.PY_MOD_2_PY_FILENAME print "Filepath of py_mod_2.py: " + os.path.join(py_mod_2.PY_MOD_2_PY_DIRECTORY_PATH, py_mod_2.PY_MOD_2_PY_FILENAME) print "Directory Path of py_mod_2.py: " + py_mod_2.PY_MOD_2_PY_DIRECTORY_PATH print "Parent Directory Path of py_mod_2.py: " + py_mod_2.PY_MOD_2_PY_PARENT_DIR print
deeper_directory/py_mod_1.py
import os PY_MOD_1_PY_FILENAME = __file__ PY_MOD_1_PY_DIRECTORY_PATH = os.path.abspath(os.path.dirname(__file__)) PY_MOD_1_PY_PARENT_DIR = os.path.abspath(os.path.join(PY_MOD_1_PY_DIRECTORY_PATH, ".."))
deeper_directory/deepest_directory/py_mod_2.py
import os PY_MOD_2_PY_FILENAME = __file__ PY_MOD_2_PY_DIRECTORY_PATH = os.path.abspath(os.path.dirname(__file__)) PY_MOD_2_PY_PARENT_DIR = os.path.abspath(os.path.join(PY_MOD_2_PY_DIRECTORY_PATH, ".."))
NOTE: Remember to put an empty __init__.py file in each directory that contains a Python Module