【发布时间】:2013-02-26 15:06:03
【问题描述】:
我正在用 python 编写一些脚本。我创建了一个保存在文件中的字符串。这个字符串有很多数据,来自目录的树状结构和文件名。 根据 convmv,我所有的树状结构都是 UTF-8。
我想将所有内容都保存在 UTF-8 中,因为之后我会将其保存在 MySQL 中。 目前,在 UTF-8 格式的 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。 有什么问题?
【问题讨论】:
-
您的python示例代码无效;至少有 2 个地方存在语法错误。请您先解决这些问题好吗?
-
您是否将文件保存为 utf-8 而不是 ascii 文件?
标签: python unicode encoding utf-8