[Django]-How to read a text file from within Django view function?

9👍

Try giving the full path to the text file.

EX:

import os

def results(request):
    module_dir = os.path.dirname(__file__)  
    file_path = os.path.join(module_dir, 'data.txt')   #full path to text.
    data_file = open(file_path , 'r')       
    data = data_file.read()
    context = {'rooms': data}
    return render(request, 'javascript/results.html',context)
👤Rakesh

0👍

def result(request)
    emails = []
    module_dir = os.path.dirname(__file__)
    file_path = os.path.join(module_dir, 'disposable.txt')
    disposable_mails = open(file_path, 'r+')
    for disposable_mail in disposable_mails:
        emails.append(disposable_mail.rstrip())

Leave a comment