python/flask在flask中打开一个文本文件

1 python flask

使用open(url_for('static',filename ='bmidata.txt')作为f:

上面的行会导致语法错误(标记为'as').该代码是以下内容的一部分:

@app.route('/display')
def display():
page_info = {
    'title':'Assignment Flask',
    'heading': 'Python Flask Assignment'
}
filedata = []
with open(url_for('static', filename='bmidata.txt') as f:
    for line in f:
        str = line
        dataarray = str.split(',')
        it =iter(dataarray)
        name = it.next()
        height = it.next()
        weight = it.next()
        newPerson = Person(name, height,weight)
        filedata.append(newPerson)

return render_template('display.html', info = page_info, fileinfo = filedata)
Run Code Online (Sandbox Code Playgroud)

任何帮助赞赏

Mes*_*ssa 6

在这一行:

with open(url_for('static', filename='bmidata.txt') as f:
Run Code Online (Sandbox Code Playgroud)

你错过了一个结束括号:

with open(url_for('static', filename='bmidata.txt')) as f:
Run Code Online (Sandbox Code Playgroud)

这就是SyntaxError的原因.

打开文件不起作用,因为open不接受URL.如果需要打开静态文件,请with app.open_resource('static/bmidata.txt') as f:在文件系统上使用或查找文件的路径.