[Django]-Open file in Django app

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.

👤Tadeck

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')
👤yaach

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')

Leave a comment