I am writing a unit test that needs to access an image file that I put in “fixtures” directory right under my django app directory. I want to open up this image file in my test using relative path, which would require me to get the absolute path of the django app. Is there a way to get the absolute path of the django app?
Share
Python modules (including Django apps) have a
__file__attribute that tells you the location of their__init__.pyfile on the filesystem, soshould do what you want.
In usual circumstances,
os.path.absname(appname.__path__[0]), but it’s possible for apps to change that if they want to import files in a weird way.(I do always do
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))in mysettings.py, though — makes it easy for the various settings that need to be absolute paths.)