5

So, I am trying to open an .csv file in Python using Flask. I copies the code from the Python library, but I go from one error message to the other and I don't know what I am doing wrong. The latest error code I get on the below code is: TypeError: invalid file:

Any ideas what I am doing wrong?

My Python code/Flash route is as follows:

@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")

My html/Flask code is:

{% 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 %}
Tomalak
  • 332,285
  • 67
  • 532
  • 628
Bart Koolhaas
  • 317
  • 1
  • 5
  • 14
  • which line number is associated with the error? – Matthias May 15 '17 at 15:29
  • 1
    maybe [this](http://stackoverflow.com/questions/33070395/not-able-to-parse-a-csv-file-uploaded-using-flask) helps, in any case fyi there is no difference opening a csv file with flask or with python, it's just like python. – Matthias May 15 '17 at 15:30

1 Answers1

2

The file is already open. open takes a string filename and created an open file object, but you don't need to do that because objects in request.files are already open file-like objects.

portfolios = csv.DictReader(request.files['portfolios'])
davidism
  • 121,510
  • 29
  • 395
  • 339