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 %}
Admin Console
Upload Portfolio Data
data>
Select Portfolio Upload File
Upload Security Lists
Select Security Upload File
Upload
{% 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!!
解决方案
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)