Open file in Django app
Solution 1
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.
Solution 2
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')
Solution 3
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')
Related videos on Youtube
Comments
-
Paul Hunter about 2 years
I want to open a file from a Django app using
open()
. The problem is thatopen()
seems to use whatever directory from which I run therunserver
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()
usesfoo
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 atfoo/myapp/anotherapp
simply by sayingfile = 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')
-
Furbeenator about 12 yearsJust FYI: You can also do this:
import socket
, then you can usesocket.gethostname()
to determine hostname of the system you're on. Set up your path based on which hostname is returned. -
Tadeck about 12 years@PaulHunter: Instead of
pwd + '/baz.txt'
you should useos.path.join(pwd, 'baz.txt')
. -
Paul Hunter about 12 yearsThanks again. Obviously Python is not my normal weapon of choice.
-
odedbd almost 11 yearsThis was just what I needed for my own issue. Thanks!
-
A.J. about 10 yearsWhat if you need to go one step inner. i mean what if baz.txt file is inside some folder in module_dir lets say foo/baz.txt?
-
Tadeck about 10 years@user570826: Either try
file_path = os.path.join(module_dir, 'foo/baz.txt')
orfile_path = os.path.join(module_dir, 'foo', 'baz.txt')
. -
zzy over 5 yearscan you tell my why this works .? why must use module dir by os.path.dirname(file)