Добрый день, я получаю следующее сообщение об ошибке, при попытке чтения из файла:Как правильно читать содержимое локального текстового файла в django?
Exception Type: KeyError
Exception Value:
'opened'
ошибка исходит из сильфона линии в ReadFile:
if fileHandler['opened']:
и это, как мой взгляд выглядит следующим образом: из project.settings импорта text_file из django.core.files импортировать файл из django.shortcuts импортируют визуализации
def home_view(request):
context = {'error': ''}
readFile(context)
render(request, 'index.html', context)
def readFile(context):
fileHandler = open_file(context, 'r')
if fileHandler['opened']:
file = File(fileHandler['handler'])
read_content(file, context)
file.close()
def open_file(context, mode):
try:
fileHandler = open(text_file, mode)
return {'open': True, 'handler': fileHandler}
except IOError:
context['error'] += 'Unable to open file.\n'
except:
context['error'] += 'Unexpected exception in openFile method.\n'
return {'opened':False, 'handler': None}
def read_content(file, context):
context['fileContent'] = ''
for sentence in file.chunks(10):
context['fileContent'] += sentence
и во мне настройки:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
text_file = os.path.join(BASE_DIR, 'my_file.txt')
действительно appreaciateany помощь.
Вы установили ключ как «открытый», как показано внутри функции open_file, и вы получаете доступ к «открытому» ключу, которого не существует. – Abhinav
@AbhinavI спасибо, вы его не заметили –