I'm able to export a MySQL table into a CSV file via Python csv
module but there are no utf-8 characters. (example: ????
chars insted of ąöę
).
The table data is in utf-8 format (phpMyAdmin let me see correct data).
I found some information that in Python all data should be decoded in utf-8 and then encoded into CSV in utf-8 via for example unicodewritter
(because the native csv
module doesn't support Unicode correctly).
I tried a lot but no success.
Question : Is there any example script to export MySQL database in utf-8 to CSV file in utf-8 format in Python?
I use ubuntu 14.04 and there is a problem with mysql.connector so I use MySQLdb with Gord Thompson code :
# -*- coding: utf-8 -*-
import csv
import MySQLdb
from UnicodeSupportForCsv import UnicodeWriter
import sys
reload(sys)
sys.setdefaultencoding('utf8')
#sys.setdefaultencoding('Cp1252')
conn = MySQLdb.Connection(db='sampledb', host='localhost',
user='sampleuser', passwd='samplepass')
crsr = conn.cursor()
crsr.execute("SELECT * FROM rfid")
with open(r'test.csv', 'wb') as csvfile:
uw = UnicodeWriter(
csvfile, delimiter=',',
quotechar='"', quoting=csv.QUOTE_MINIMAL)
for row in crsr.fetchall():
uw.writerow([unicode(col) for col in row])
Error still exist : UnicodeDecodeError: 'utf8' codec can't decode byte 0xf3 in position 2: invalid continuation byte
UnicodeWriter
class shown at the very bottom of the documentation page for the csv module? I've used it with Python 2.7 and it worked fine for me. – Gord Thompson