gpt4 book ai didi

python - 使用Flask通过浏览器加载一个txt文件并访问其数据进行处理

转载 作者:太空宇宙 更新时间:2023-11-04 03:04:46 26 4
gpt4 key购买 nike

我正在制作一个数据可视化工具,它接受用户的输入(在计算机上选择一个文件);使用 Pandas、Numpy 等在 Python 中处理它;并在本地服务器的浏览器中显示数据。

使用 HTML 输入表单选择文件后,我无法访问数据。

HTML 格式:

<form action="getfile" method="POST" enctype="multipart/form-data">
Project file path: <input type="file" name="myfile"><br>
<input type="submit" value="Submit">
</form>

flask 路由:

@app.route("/")
def index():
return render_template('index.html')

@app.route('/getfile', methods=['GET','POST'])
def getfile():
if request.method == 'POST':
result = request.form['myfile']
else:
result = request.args.get['myfile']
return result

这将返回“错误请求浏览器(或代理)发送了该服务器无法理解的请求。”错误。我已经尝试了多种不同的方法来从文件中获取数据并简单地将其打印到屏幕上以开始,并且收到了一系列错误,包括“TypeError:'FileStorage'对象不可调用”和“ImmutableMultiDict'对象不可调用”。任何有关如何正确处理此任务的指示都将受到赞赏。

最佳答案

试试这个。最近几天我一直在保存和解压缩文件。如果您对这段代码有任何疑问,请告诉我:)

我建议将文件保存在磁盘上然后读取它。如果您不想这样做,则不需要。

from flask import Flask, render_template, request
from werkzeug import secure_filename

@app.route('/getfile', methods=['GET','POST'])
def getfile():
if request.method == 'POST':

# for secure filenames. Read the documentation.
file = request.files['myfile']
filename = secure_filename(file.filename)

# os.path.join is used so that paths work in every operating system
file.save(os.path.join("wherever","you","want",filename))

# You should use os.path.join here too.
with open("wherever/you/want/filename") as f:
file_content = f.read()

return file_content


else:
result = request.args.get['myfile']
return result

正如 zvone 在评论中建议的那样,我也建议不要使用 GET 上传文件。

Uploading files
os.path by Effbot

编辑:-

您不想保存文件。

Uploaded files are stored in memory or at a temporary location on the filesystem. You can access those files by looking at the files attribute on the request object. Each uploaded file is stored in that dictionary. It behaves just like a standard Python file object, but it also has a save() method that allows you to store that file on the filesystem of the server.

我从 Flask 文档中得到了这个。由于它是一个 Python 文件,您可以直接在其上使用 file.read() 而无需 file.save()

另外,如果您需要保存一段时间然后删除它,您可以在保存后使用os.path.remove 删除文件。 Deleting a file in Python

关于python - 使用Flask通过浏览器加载一个txt文件并访问其数据进行处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39801728/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com