如何使用Flask将文本文件读入我的.py文件,然后获得逐行数组? [重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

请看这里我的命令行输出:(https://i.stack.imgur.com/l8Qbl.jpg

它说文件/static/poemInput.txt不存在..但正如你所看到的,当我执行ls static时它显然存在。我是如何命名文件的?

上下文:我是新手,但我有一个我想在线部署的python应用程序。我只是想导入我在应用程序中使用的文本文件,但是找不到它。

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

我得到了错误指定here所以我的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函数中修改(就像在我的原始代码中一样)...我怎么能用flask的open_resource函数做到这一点?我尝试做f.encode('latin1')但我得到错误:_io.TextIOWrapper' object has no attribute 'encode'

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

python-3.x flask url-for
1个回答
0
投票

问题

问题出在你的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)
© www.soinside.com 2019 - 2024. All rights reserved.