12944qwerty
12944qwerty

Reputation: 2007

How to open file in django

I'm trying to open a file that is in the same directory as the app from views.

-app
--views.py
--about.txt
--...

My code to open the file is..

def home(request):
    with open('about.txt','r') as f:
        about = f
    about = about.split('\n')
    about = '<br/>'.join(about)
    return render(request, 'app/home.html', {'about':about})

But I keep getting an error of `

FileNotFoundError at /
[Errno 2] No such file or directory: 'about.txt'

After thinking about this, I thought of putting it in a static dir but it would still give the same error.

Edit: I don't know if this is the reason... but when pressing enter for new line, it makes it on a new indentation.example

Upvotes: 0

Views: 3806

Answers (1)

Calder White
Calder White

Reputation: 1326

TL;DR

You have to prepend your path with something like app to create app/about.txt. I have insufficient information to tell you exactly what, but here is how to find out:

When you run your app, the working directory is probably not in app. You can figure out what path it is running in by using os.getcwd(). For example:

import os

# ...

def home(request):
    print(os.getcwd())
    with open('about.txt','r') as f:
        about = f
    about = about.split('\n')
    about = '<br/>'.join(about)
    return render(request, 'app/home.html', {'about':about})

As @KlausD. mentioned, your path is relative. Whenever code is being run, it is run in a "working directory". For example, if I ran python views.py in the app directory, the current working directory (cwd for short) would be app. Then, when a relative path is given, like about.txt (which really means ./about.txt, where . represents the cwd), it looks in the cwd for about.txt.

Upvotes: 3

Related Questions