Bart Koolhaas
Bart Koolhaas

Reputation: 351

Opening csv file in Python: builtins. AttributeError AttributeError: '_io.BytesIO' object has no attribute 'file'

further to my earlier question, on how to open an csv file in Python, I am still not successful in doing so and going from error to error.

My Python code 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
    csvfile = TextIOWrapper(request.files['portfolios'].file, encoding=request.encoding)
    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 flask/html code is as follows:

{% 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 %}

Initially, I literally followed the example from the Python documentation: import csv with open('names.csv') as csvfile: reader = csv.DictReader(csvfile) for row in reader: print(row['first_name'], row['last_name'])

this didnt work as it gave a type error (see my earlier post)

I then removed, as suggested, the "open", which resulted in another error. I then removed the whole with block, which again resulted in an error. Now, the above code is what I am now, and its generating the following error:

builtins.AttributeError AttributeError: '_io.BytesIO' object has no attribute 'file'

Anyone who can help my csv import nightmare to end?? Txs!!

Upvotes: 1

Views: 6434

Answers (1)

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140196

io.TextIOWrapper takes a io.BytesIO object all right.

You're (almost) passing it, except that you're adding a .file (why??), which is not a field of the io.BytesIO class (request.files['portfolios'] is a io.BytesIO object already)

Just do:

csvfile = TextIOWrapper(request.files['portfolios'], encoding=request.encoding)

Upvotes: 1

Related Questions