我是烧瓶的新手。我试图使用flask将csv文件中的数据上传到MySQL。但是我收到一个错误“ _csv.Error:迭代器应返回字符串,而不是字节(您是否以文本模式打开文件?)”。如何解决?
我的代码是:
from flask import Flask,render_template, url_for, request, redirect
from flask_wtf import FlaskForm, Form
from wtforms import StringField,SubmitField
import csv
from flask_mysqldb import MySQL
myd = MySQLdb.connect(host='localhost',user='root',passwd='admin',db='user')
cur = myd.cursor()
app = Flask(__name__)
app.config['SECRET_KEY'] = '7e46de54884a3803d8bc35a52d6a6ae8'
@app.route("/uploaddb", methods=['GET','POST'])
def updb():
files = request.files['file']
reader = csv.DictReader(files)
data = [row for row in reader]
for row in data:
systemid = row['systemid']
school=row['school']
phone=row['phone']
address=row['address']
state=row['state']
cur.execute("INSERT INTO
testcsv(systemid,school,phone,address,state)"
"VALUES('%s','%s','%s','%s','%s','%s')",systemid,school,phone,address,state)
myd.commit()
cur.close()
if __name__ == '__main__':
app.run()
答案 0 :(得分:0)
我认为,您可能需要以utf-8编码模式读取CSV文件才能将字节转换为字符串