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 %}
2
  • which line number is associated with the error? Commented May 15, 2017 at 15:29
  • 1
    maybe this helps, in any case fyi there is no difference opening a csv file with flask or with python, it's just like python. Commented May 15, 2017 at 15:30

1 Answer 1

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'])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.