栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

无法解析使用Flask上传的.csv文件

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

无法解析使用Flask上传的.csv文件

因此你的脚本存在一个主要问题,

csv.reader
如此处所述,它需要一个文件对象或至少一个支持迭代器协议的对象。你传递的str确实实现了迭代器协议,但是与其遍历各行,而是遍历这些字符,而不是遍历这些行。这就是为什么要执行输出的原因。

首先,它给出一个单一字符1,该字符

csv.reader
被视为具有一个字段的线。之后,str给出另一个字符,,该字符
csv.reader
被视为带有两个空字段的行(因为逗号是字段分隔符)。整个过程
str
一直如此,直到用尽为止。

解决方案(或至少一种解决方案)是将str变成一个文件状对象。我尝试使用所提供的流

flask.request.files["name"]
,但这并没有遍历所有行。接下来,我尝试使用
cStringIO.StringIO
和似乎有类似的问题。我最终想到了这个问题,该问题建议使用
io.StringIO
通用换行模式的对象起作用。我最终得到了以下工作代码(也许可能会更好):

__author__ = 'shivendra'from flask import Flask, make_response, requestimport ioimport csvapp = Flask(__name__)def transform(text_file_contents):    return text_file_contents.replace("=", ",")@app.route('/')def form():    return """        <html> <body>     <h1>Transform a file demo</h1>     <form action="/transform" method="post" enctype="multipart/form-data">         <input type="file" name="data_file" />         <input type="submit" />     </form> </body>        </html>    """@app.route('/transform', methods=["POST"])def transform_view():    f = request.files['data_file']    if not f:        return "No file"    stream = io.StringIO(f.stream.read().depre("UTF8"), newline=None)    csv_input = csv.reader(stream)    #print("file contents: ", file_contents)    #print(type(file_contents))    print(csv_input)    for row in csv_input:        print(row)    stream.seek(0)    result = transform(stream.read())    response = make_response(result)    response.headers["Content-Disposition"] = "attachment; filename=result.csv"    return responseif __name__ == "__main__":    app.run(host='0.0.0.0', port=5001, debug=True)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/386332.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号