Pythonでいくつかのスクリプトを実行しています。ファイルに保存する文字列を作成します。この文字列は、ディレクトリの樹木とファイル名に由来する多くのデータを取得しています。convmv によると、私の樹木はすべて UTF-8 です。
後でMySQLに保存するので、すべてをUTF-8に保ちたいです。今のところ、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 に書き込みます。何が問題ですか ?