My django app has to read some text files from the file system. So I make a directory in my app directery, and use relative path to open and read from the file.
areas = parseXmlFile('xml_files/area.xml')
When I run server to debug using manage.py runserver
, that's ok. But I run server using manage.py runfcgi host=127.0.0.1 port=8081
, Django can't find the file: No such file or directory: 'xml_files/area.xml'
I don't want to use absolute path, that means I need to modify much code.
How can I solve the problem to use relative path to open local file?
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 os settings_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_FOLDER path = 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 os from yourproject.settings import BASE_DIR file_path = os.path.join(BASE_DIR, 'relative_path')
Bear in mind that the relative path is from your Django project's root folder.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With