If you like to load the code you're working via import
by putting its project directory under your PYTHONPATH, and the code depends on data files you've stored in the project directory, you can use __file__
to get the project location and retrieve the data.
I like to load everything I work on via import
, but my coworkers run the scripts I give them inside their project directories from the command line. So in these scripts I use a getwd
function defined as follows to get the correct location of the project files, regardless of how the script is run:
import os
def getwd():
return os.path.dirname(__file__) if '__file__' in globals() else os.getcwd()
When I load the script via import
, getwd
returns the directory of the script. When my coworkers run the script from the command line inside their project directory, there is no global __file__
, and getwd
simply returns the current directory.