53👍
✅
The solution has been described in the Favorite Django Tips&Tricks question. The solution is as follows:
import os
module_dir = os.path.dirname(__file__) # get current directory
file_path = os.path.join(module_dir, 'baz.txt')
Which does exactly what you mentioned.
Ps. Please do not overwrite file
variable, it is one of the builtins.
2👍
I had a similar case. From inside my views.py I needed to open a file sitting in a directory at the same level of my app:
-- myapp
-- views.py # Where I need to open the file
-- testdata
-- test.txt # File to be opened
To solve I used the BASE_DIR settings variable to reference the project path as follows
...
from django.conf import settings
...
file_path = os.path.join(settings.BASE_DIR, 'testdata/test.txt')
- [Django]-How to dynamically set the queryset of a models.ModelChoiceField on a forms.Form subclass
- [Django]-In Django models.py, what's the difference between default, null, and blank?
- [Django]-How to use MySQLdb with Python and Django in OSX 10.6?
1👍
I think I found the answer through another stack overflow question (yes, I did search before asking…)
I now do this
pwd = os.path.dirname(__file__)
file = open(pwd + '/baz.txt')
- [Django]-How to handle request.GET with multiple variables for the same parameter in Django
- [Django]-How to pass a variable from settings.py to a view?
- [Django]-How to see details of Django errors with Gunicorn?
Source:stackexchange.com