1

I have a Django project called myproject, which has an app called myapp. I want to read a text file and load its contents into a list. I'm a little confused about static files and relative directories in Django, and my initial attempt is not working. So far, I have the following code...

In /myproject/settings.py:

STATIC_URL = '/static/'

In /myapp/static/myapp, there is a file called myfile.txt.

In /myapp/views.py:

with open('myapp/myfile.txt') as f:
    lines = f.readlines()

When running the server, I get the error: No such file or directory: 'myapp/myfile.txt'

What am I doing wrong?

EddyJ
  • 117
  • 2
  • 9

1 Answers1

1

in your settings:

import os
gettext = lambda s: s
PROJECT_PATH = os.path.normpath(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..'))
MEDIA_ROOT = os.path.join(PROJECT_PATH, "media")
MEDIA_URL = "/media/"

create a folder media under your app folder.

then put the file you want to read in that folder.

and try this in your views.py:

from django.conf import settings
with open(settings.MEDIA_ROOT + '\\yourfile.text', 'rb') as f:
  lines = f.readlines()
doniyor
  • 36,596
  • 57
  • 175
  • 260