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')
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.
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.
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.
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.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With