Python 如何在django中正确读取本地文本文件内容?
您好,我在尝试读取文件时收到以下错误:Python 如何在django中正确读取本地文本文件内容?,python,django,Python,Django,您好,我在尝试读取文件时收到以下错误: Exception Type: KeyError Exception Value: 'opened' 错误来自readFile中的以下行: if fileHandler['opened']: 这就是我的观点: 从project.settings导入文本文件 从django.core.files导入文件 从django.shortcuts导入渲染 def home_view(request): context = {'error': ''
Exception Type: KeyError
Exception Value:
'opened'
错误来自readFile中的以下行:
if fileHandler['opened']:
这就是我的观点:
从project.settings导入文本文件
从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
在me设置中:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
text_file = os.path.join(BASE_DIR, 'my_file.txt')
将非常感谢您的帮助。我在视图的第三行中没有看到函数readFile的声明
def home_view(request):
context = {'error': ''}
readFile(context) # HERE!
render(request, 'index.html', context)
可能是您的问题在这里?很抱歉,键入错误,我已将其替换。您已将“打开”文件函数中的键设置为“打开”,并且正在访问一个不存在的“打开”键。@AbhinavI谢谢您没有注意到它