21
votes

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

2 Answers

43
votes

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.

1
votes

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