python 编码 utf-8

10 浏览
0 Comments

python 编码 utf-8

我正在用Python编写一些脚本。我创建了一个字符串,将其保存在一个文件中。这个字符串包含很多数据,来自目录的层次结构和文件名。

根据convmv的说法,我的整个目录结构都是UTF-8编码的。

我希望保持所有内容都是UTF-8编码,因为我之后要将其保存在MySQL中。

目前,在MySQL中,我遇到了一些字符的问题(比如é或è - 我是法国人)。

我希望Python始终使用UTF-8编码的字符串。我在互联网上阅读了一些信息,然后我按照以下方式进行了操作。

我的脚本从以下内容开始:

 #!/usr/bin/python
 # -*- coding: utf-8 -*-
 def createIndex():
     import codecs
     toUtf8=codecs.getencoder('UTF8')
     #很多操作和构建indexSTR的字符串
     findex=open('config/index/music_vibration_'+date+'.index','a')
     findex.write(codecs.BOM_UTF8)
     findex.write(toUtf8(indexSTR)) #这里有问题!

然后当我执行时,出现了以下错误: UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 2171: ordinal not in range(128)

编辑:

我看到我的文件中的重音符号写得很好。创建了这个文件后,我读取它并将其写入MySQL中。

但是不知道为什么,我遇到了编码问题。

我的MySQL数据库是UTF-8编码的,或者看起来是的。SQL查询SHOW variables LIKE 'char%'只返回utf8或binary。

我的函数看起来像这样:

#!/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')

而在文件中显示得很好的艺术家名字在数据库中却显示错误。

问题出在哪里?

0