Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open file in Django app

Tags:

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') 
like image 591
Paul Hunter Avatar asked Mar 14 '12 22:03

Paul Hunter


People also ask

How do I view files in Django?

There is a file called urls.py on the myworld folder, open that file and add the include module in the import statement, and also add a path() function in the urlpatterns[] list, with arguments that will route users that comes in via 127.0. 0.1:8000/members/ . In the browser window, type 127.0.

How do I open a TXT file in Django?

Django File ObjectThe open() function opens the file in the given mode argument, and the write() method is used to write a file, and the read() method is used to read a file. At last, we have closed the file object and file using close() method. Here is the complete code to write and read a file.

How do I serve media files in Django?

Media Files in Development Mode Unfortunately, the Django development server doesn't serve media files by default. Fortunately, there's a very simple workaround: You can add the media root as a static path to the ROOT_URLCONF in your project-level URLs.


2 Answers

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.

like image 86
Tadeck Avatar answered Sep 22 '22 12:09

Tadeck


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') 
like image 45
Paul Hunter Avatar answered Sep 24 '22 12:09

Paul Hunter