How can I use relative path to read local files in Django app?
I'll suggest you to use absolute path
but in a more clever way. Declare in your settings.py
something like XMLFILES_FOLDER
and have your settings.py
like this:
import ossettings_dir = os.path.dirname(__file__)PROJECT_ROOT = os.path.abspath(os.path.dirname(settings_dir))XMLFILES_FOLDER = os.path.join(PROJECT_ROOT, 'xml_files/')
This is assuming that xml_files
folder lives under the project root folder, if not, just declare the relative path from the project root folder to the xml_files
XMLFILES_FOLDER = os.path.join(PROJECT_ROOT, 'f1/f2/xml_files/')
That way, wherever in your code you want to access a file inside that directory you just do:
from settings import XMLFILES_FOLDERpath = XMLFILES_FOLDER+'area.xml'
This approach will work in any OS, and no matter you change the folder of the project, it will still work.
Hope this helps!
@Paulo Bu's answer is correct, but outdated. Modern-day settings.py files have a BASE_DIR variable you can use for this endeavour.
import osfrom yourproject.settings import BASE_DIRfile_path = os.path.join(BASE_DIR, 'relative_path')
Bear in mind that the relative path is from your Django project's root folder.