打开已在Flask中上传的文件 [英] Opening a file that has been uploaded in Flask
问题描述
我正在尝试修改上传到我的Flask应用程序中的csv.当我不通过烧瓶上载它时,我的逻辑工作得很好.
I'm trying to modify a csv that is uploaded into my flask application. I have the logic that works just fine when I don't upload it through flask.
import pandas as pd
import StringIO
with open('example.csv') as f:
data = f.read()
data = data.replace(',"', ",'")
data = data.replace('",', "',")
df = pd.read_csv(StringIO.StringIO(data), header=None, sep=',', quotechar="'")
print df.head(10)
我将其上传到烧瓶并使用
I upload it to flask and access it using
f = request.files['data_file']
通过上面的代码运行它,将open('example.csv')替换为open(f)时,出现以下错误
When I run it through the code above, replacing open('example.csv') with open(f), I get the following error
coercing to Unicode: need string or buffer, FileStorage found
我发现问题出在这里是文件类型.我无法在文件上使用open,因为open正在寻找文件名,并且当文件上传到flask时,它是要传递给open命令的文件实例.但是,我不知道该如何做.我试过跳过open命令,仅使用data = f.read(),但这不起作用.有什么建议吗?
I have figured out that the problem is the file type here. I can't use open on my file because open is looking for a file name and when the file is uploaded to flask it is the instance of the file that is being passed to the open command. However, I don't know how to make this work. I've tried skipping the open command and just using data = f.read() but that doesn't work. Any suggestions?
谢谢
推荐答案
回答我自己的问题,以防别人需要.
Answering my own question in case someone else needs this.
FileStorage对象具有.stream属性,该属性将是io.BytesIO
FileStorage objects have a .stream attribute which will be an io.BytesIO
f = request.files['data_file']
df = pandas.read_csv(f.stream)
这篇关于打开已在Flask中上传的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!