0
良い一日、私は、次のエラーを受信しています:djangoのローカルテキストファイルの内容を正しく読み込むには?ファイルから読み取るしようとしているときに
Exception Type: KeyError
Exception Value:
'opened'
エラーがreadFileので怒鳴るラインから来ている:
if fileHandler['opened']:
と、これはどのようにあります以下のように私の見解はなりますproject.settingsから がdjango.core.filesから TEXT_FILEインポート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
0123をレンダリングインポートの
と私の設定:
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関数の内部にあるように、キーを 'open'に設定していて、存在しない 'opened'キーにアクセスしています。 – Abhinav
@Abhinavありがとうございましたありがとうございました –