美好的一天,我在尝试从文件中读取时收到以下错误:
Exception Type: KeyError
Exception Value:
'opened'
错误来自readFile中的下面一行:
if fileHandler['opened']:
这就是我的观点: 来自project.settings import 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')
真的会有所帮助。
答案 0 :(得分:0)
我在视图的第三行看不到函数readFile的声明!
def home_view(request):
context = {'error': ''}
readFile(context) # HERE!
render(request, 'index.html', context)
也许你的问题在这里?