Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在django中正确读取本地文本文件内容?_Python_Django - Fatal编程技术网

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谢谢您没有注意到它