根据convmv的说法,我的整个目录结构都是UTF-8编码的。
我希望保持所有内容都是UTF-8编码,因为我之后会将它保存到MySQL中。但是现在,在MySQL中出现了一些字符问题(比如é或è - 我是法国人)。
我希望Python始终将字符串作为UTF-8使用。我在网上阅读了一些信息,然后按照以下方式进行操作。
我的脚本从这里开始:
#!/usr/bin/python
# -*- coding: utf-8 -*-
def createIndex():
import codecs
toUtf8=codecs.getencoder('UTF8')
#lot of operations & building indexSTR the string who matter
findex=open('config/index/music_vibration_'+date+'.index','a')
findex.write(codecs.BOM_UTF8)
findex.write(toUtf8(indexSTR)) #this bugs!
当我执行时,这是答案:UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 2171: ordinal not in range(128)
编辑:
我明白了,在我的文件中,重音符号写得很好。创建此文件后,我将其读取并写入MySQL。
但我不明白为什么会出现编码问题。
我的MySQL数据库是utf8的,或者似乎是SQL查询SHOW variables LIKE 'char%'
只返回utf8或二进制。
我的函数看起来像这样:
#!/usr/bin/python
# -*- coding: utf-8 -*-
def saveIndex(index,date):
import MySQLdb as mdb
import codecs
sql = mdb.connect('localhost','admin','*******','music_vibration')
sql.charset="utf8"
findex=open('config/index/'+index,'r')
lines=findex.readlines()
for line in lines:
if line.find('#artiste') != -1:
artiste=line.split('[:::]')
artiste=artiste[1].replace('\n','')
c=sql.cursor()
c.execute('SELECT COUNT(id) AS nbr FROM artistes WHERE nom="'+artiste+'"')
nbr=c.fetchone()
if nbr[0]==0:
c=sql.cursor()
iArt+=1
c.execute('INSERT INTO artistes(nom,status,path) VALUES("'+artiste+'",99,"'+artiste+'/")'.encode('utf8')
一个艺术家在文件中被很好地展示,但是写入BDD时出现了问题。问题是什么?