Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a media file from .py file using Django?

I can read a.txt file like this:

text = open('a.txt', 'rb').read()

But when I put the a.txt to the media folder, this doesn't work:

text = open('/media/a.txt', 'rb').read()

I'm getting the following error:

IOError at /
[Errno 13] file not accessible: '/media/a.txt'

How can I read file from the media directory?

like image 599
zjm1126 Avatar asked Dec 29 '22 19:12

zjm1126


1 Answers

To be more generic (and be sure that you use the media folder), you could change it to:

import os
from django.conf import settings
text = open(os.path.join(settings.MEDIA_ROOT, 'a.txt'), 'rb').read()
like image 181
Gert Avatar answered Jan 10 '23 12:01

Gert