使用Flask在Python中打开csv文件

时间:2017-05-15 13:09:59

标签: python csv flask

所以,我正在尝试使用Flask在Python中打开一个.csv文件。我从Python库中复制代码,但是我从一条错误消息转到另一条错误消息,我不知道我做错了什么。我在下面的代码中得到的最新错误代码是:TypeError:无效文件:

任何想法我做错了什么?

我的Python代码/ Flash路由如下:

@app.route("/admin", methods=["GET", "POST"])
@login_required
def admin():
    """Configure Admin Screen"""
    # if user reached route via POST (as by submitting a form via POST)
    if request.method == "POST":

        # load csv file with portfolio data
        with open(request.files["portfolios"]) as csvfile:
            portfolios = csv.DictReader(csvfile)

        # load csv file in dictionary
        for row in portfolios:
            print(row['first_name'], row['last_name'])
    else:
        return render_template("admin.html")

我的html / Flask代码是:

{% extends "layout.html" %}

{% block title %}
    Admin
{% endblock %}

{% block main %}
<h2>Admin Console</h2>
<h3> Upload Portfolio Data</h2>
<form action="{{ url_for('admin') }}" method="post" enctype=multipart/form-data>
    <fieldset>
        <label class="control-label">Select Portfolio Upload File</label>
        <input id="input-1" type="file" class="file" name="portfolios">
        <h3>Upload Security Lists</h2>
        <label class="control-label">Select Security Upload File</label>
        <input id="input-1" type="file" class="file" name="securities">
        <div class="form-group">
            <button class="btn btn-default" type="submit" value = "upload">Upload</button>
        </div>
    </fieldset>
</form>
{% endblock %}

1 个答案:

答案 0 :(得分:1)

该文件已经打开。 open采用字符串文件名并创建一个打开的文件对象,但您不需要这样做,因为request.files中的对象已经是打开的文件对象。

portfolios = csv.DictReader(request.files['portfolios'])