UnicodeEncodeError:'ascii' 编码无法在导出 CSV 到 MySQL 时编码
我正在尝试将CSV文件导入到MySQL数据库中,但每次我尝试打印时都会收到错误信息。希望能得到一些帮助。我不知道自己哪里出错了……
reader = csv.reader(open(csvfile, 'r'))
for row in reader:
print row
try:
(location_id, vrm, valid_datetime) = row
except:
print "Error with row: " % row
#sys.exit(3)
# Hack for Roseburys
if (location_id == 262):
location_id = "198"
if (location_id == "262"):
location_id = "198"
tmp = valid_datetime.split(" ")
valid_date = tmp[0]
# Tidy up the VRM
vrm = vrm.replace(' ', '')
vrm = vrm.upper()
tmp = valid_date.split('/')
iso_date = "%s-%s-%s" % (tmp[2], tmp[1], tmp[0])
entryDatetime = "%s 00:00:00" % iso_date
expiryDatetime = "%s 23:59:59" % iso_date
sql_local = """INSERT INTO customer_1.pay_and_display
(plate, machine_id, ticket_datetime, expiry_datetime, ticket_name, ticket_price)
VALUES ("%s", "%s", "%s", "%s", "%s", "%s") """ % (vrm, location_id, entryDatetime, expiryDatetime, "WL", 0)
print sql_local
cursor.execute(sql_local)
1 个回答
0
这行代码的意思是:我们要打开一个CSV文件(就是一种用逗号分隔的数据文件),然后用一个叫做“reader”的工具来读取这个文件里的内容。这里的“csv.reader”就是那个工具,而“open(csvfile, 'r')”是打开文件的方式,'r'表示我们是以只读的方式打开它。
for row in reader:
print row
try:
(location_id, vrm, valid_datetime) = row
except:
print "Error with row: " % row
#sys.exit(3)
# Hack for Roseburys
if (location_id == 262):
location_id = "198"
if (location_id == "262"):
location_id = "198"
tmp = valid_datetime.split(" ")
valid_date = tmp[0]
# Tidy up the VRM
vrm = vrm.replace(' ', '')
vrm = vrm.upper()
tmp = valid_date.split('/')
iso_date = "%s-%s-%s" % (tmp[2], tmp[1], tmp[0])
entryDatetime = "%s 00:00:00" % iso_date
expiryDatetime = "%s 23:59:59" % iso_date
sql_local = """INSERT INTO customer_1.pay_and_display
(plate, machine_id, ticket_datetime, expiry_datetime, ticket_name, ticket_price)
VALUES ("%s", "%s", "%s", "%s", "%s", "%s") """ % (vrm, location_id, entryDatetime, expiryDatetime, "WL", 0)
print sql_local
cursor.execute(sql_local)