python-3.x - 如何使用 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 文件,然后获取逐行数组?
解决方案
问题
问题出在你的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)
推荐阅读
- spring-boot - 强制 SpingBoot 使用 Gson 而不是 Jackson
- android - 如何在 android paging 3 库中标记数据集的结尾?
- nest-device-access - 直播的替代格式
- javascript - 使用 ui.router 无法使用 HTTP Post 的回调 url
- sql - PLSQL Total 字段的问题 - 不计算
- python - 如何删除同时具有分类数据和数值数据的数据集中的异常值?
- docker - 在 docker compose 中的容器之间共享 FUSE 挂载,而不在主机上保留任何内容
- r - Ubuntu 20.04 上 R 3.6 的“minfi”包安装不成功
- python - 如何解决熊猫求和行之类的字符串,而不是数字?
- ios - 如何使用swift为Ipad设计一个按高度覆盖一半屏幕的框架?