首页 > 解决方案 > 如何使用 Flask 将文本文件读入我的 .py 文件,然后获取逐行数组?

问题描述

请在此处查看我的命令行输出:(https://i.stack.imgur.com/l8Qbl.jpg

它说文件 /static/poemInput.txt 不存在.. 但正如你所看到的,当我执行ls static. 我如何命名文件有问题吗?

上下文:我对烧瓶很陌生,但我有一个想要在线部署的 python 应用程序。我只是想导入我在应用程序中使用的文本文件,但是找不到。

我知道文本文件应该在静态文件夹中,并且我根据需要使用了 open_url。

我得到了这里指定的错误,所以我with open的块在一个with.app.test_request_context():块内。

编辑 我尝试了 Luan Nguyen 的建议并使用了该app.open_resource()功能,但后来我得到了一个UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 13: ordinal not in range(128). 这已通过将编码设置为 latin1 在 python 的 open 函数(如我的原始代码中)中修复......我如何使用烧瓶的 open_resource 函数来做到这一点?我试着做f.encode('latin1'),但我得到了错误:_io.TextIOWrapper' object has no attribute 'encode'

本质上:如何使用 Flask 将文本文件读入我的 .py 文件,然后获取逐行数组?

标签: python-3.xflaskurl-for

解决方案


问题

问题出在你的open电话上。url_for返回此字符串'/static/poemInput.txt'。当你将此字符串直接放入 Python 的时,它会在open找到文件,而不是在 处 <system_root>/static/poemInput.txt <your_project_directory>/static/poemInput.txt

解决方案

鉴于您可能有一个正在运行的 Flask 实例,您应该使用 Flask 的open_resource功能。使用这种结构:

/myapplication.py
/schema.sql
/static
    /poemInput.txt
    /style.css
/templates
    /layout.html
    /index.html

您可以执行以下操作:

with app.open_resource('static/poemInput.txt') as f:
    contents = f.read()
    do_something_with(contents)

推荐阅读