您不需要对 已经 编码的数据进行编码。当您尝试执行此操作时,Python会先尝试对其进行 解码 ,unicode
然后再将其编码回UTF-8。这就是这里失败的原因:
>>> data = u'\u00c3' # Unicode data
>>> data = data.encode('utf8') # encoded to UTF-8
>>> data
'\xc3\x83'
>>> data.encode('utf8') # Try to *re*-encode it
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)
只需直接写您的数据文件,也 没有 必要编码已编码的数据。
如果改为建立unicode
值,则实际上必须将那些值编码为可写入文件。您想使用codecs.open()
它,它返回一个文件对象,该文件对象将为您将Unicode值编码为UTF-8。
您也 确实 不想写UTF-8 BOM, 除非 您 必须 支持否则无法读取UTF-8的Microsoft工具(例如MS Notepad)。
添加charset='utf8'
到您的MysqLdb.connect()
通话中。
使用unicode
对象,而不是str
查询或插入对象,而是 使用sql参数, 以便MysqL连接器可以为您做正确的事情:
artiste = artiste.decode('utf8') # it is already UTF8, decode to unicode
c.execute(‘SELECT COUNT(id) AS nbr FROM artistes WHERE nom=%s’, (artiste,))
c.execute(‘INSERT INTO artistes(nom,status,path) VALUES(%s, 99, %s)’, (artiste, artiste + u’/’))
如果您codecs.open()
改为自动解码内容,则实际上可能会更好:
import codecs
sql = mdb.connect('localhost','admin','ugo&(-@F','music_vibration', charset='utf8')
with codecs.open('config/index/'+index, 'r', 'utf8') as findex:
for line in findex:
if u'#artiste' not in line:
continue
artiste=line.split(u'[:::]')[1].strip()
cursor = sql.cursor()
cursor.execute('SELECT COUNT(id) AS nbr FROM artistes WHERE nom=%s', (artiste,))
if not cursor.fetchone()[0]:
cursor = sql.cursor()
cursor.execute('INSERT INTO artistes(nom,status,path) VALUES(%s, 99, %s)', (artiste, artiste + u'/'))
artists_inserted += 1
您可能需要复习Unicode和UTF-8和编码。我可以推荐以下文章:
Ned Batchelder的实用Unicode
每个软件开发人员绝对,肯定必须绝对了解Unicode和字符集(无借口!)作者:Joel Spolsky