使用csv writer和MySQLdb忽略编码错误

时间:2018-04-27 09:42:00

标签: python csv mysql-python

我一直在尝试使用python从MySQL表中获取完整的数据到csv并且我已经做得很好但是现在该表有一个列“描述”并且它现在是一块地狱因为它有编码各地都有问题。

在尝试了从其他帖子中获取的吨和大量的东西后,现在我放弃了这些字符,我想直接跳过它们并避免这些错误。

test.py:

import MySQLdb, csv, codecs
dbConn = MySQLdb.connect(dbServer,dbUser,dbPass,dbName,charset='utf8')
cur = dbConn.cursor()
def createFile(self):
    SQLview = 'SELECT fruit_type, fruit_qty, fruit_price, fruit_description FROM fruits'
    cur.execute(SQLview)
    with codecs.open('fruits.csv','wb',encoding='utf8',errors='ignore') as csv_file:
    csv_writer = csv.writer(csv_file)
    csv_writer.writerows(cur)

仍然从函数中得到错误:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xd1' in position 27: ordinal not in range(128)

我是否可以跳过该错误并仍然从DB Query中写入其余数据?

PD:功能崩溃线是:

csv_writer.writerows(cur)

不知道这对某人是否有用

1 个答案:

答案 0 :(得分:1)

终于解决了

改变:

import csv

为:

import unicodecsv as csv

改变:

csv_writer = csv.writer(csv_file)

为:

csv_writer = csv.writer(csv_file,encoding='utf-8')