Paul Hunter
Paul Hunter

Reputation: 4463

Open file in Django app

I want to open a file from a Django app using open(). The problem is that open() seems to use whatever directory from which I run the runserver command as the root.

E.g. if I run the server from a directory called foo like this

$pwd
/Users/foo
$python myapp/manage.py runserver

open() uses foo as the root directory.

If I do this instead

$cd myapp
$pwd
/Users/foo/myapp
$python manage.py runserver

myapp will be the root.

Let's say my folder structure looks like this

foo/myapp/anotherapp

I would like to be able to open a file located at foo/myapp/anotherapp from a script also located at foo/myapp/anotherapp simply by saying

file = open('./baz.txt')

Now, depending on where I run the server from, I have to say either

file = open('./myapp/anotherapp/baz.txt')

or

file = open('./anotherapp/baz.txt')

Upvotes: 29

Views: 42813

Answers (3)

yaach
yaach

Reputation: 462

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

Upvotes: 3

Tadeck
Tadeck

Reputation: 137320

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.

Upvotes: 54

Paul Hunter
Paul Hunter

Reputation: 4463

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

Upvotes: 1

Related Questions