import MySQLdb as mdb
import csv
db_user = 'root'
db_pass = 'FGifPYRMcuQYF3dh'
db_schema = 'site1.local'
dbs = {
'db1': 'localhost'
}
def export_csv_accounts():
con = None
for dbnames in dbs:
con = mdb.connect(dbs[dbnames], db_user, db_pass, db_schema)
cur = con.cursor()
db_query = "select * from tabAccount;"
cur.execute(db_query)
rows = cur.fetchall()
out_file = csv.writer(open("/home/"+dbs[dbnames] + '_Accounts.csv', "wb"))
columns = [i[0] for i in cur.description]
out_file.writerow(columns)
out_file.writerows(rows)
con.close()
return "Ok"
文件csv出错 “公司”,“LâmCh?n Huy”,“越南” 我的UTF-8文件有错误。 如何将UTF-8用于csv文件?
答案 0 :(得分:0)
Python 2的csv
模块无法正确处理Unicode CSV文件,您可以see in the documentation。尝试使用the code examples
UnicodeWriter
和UnicodeReader
类
答案 1 :(得分:0)
在写入文件之前尝试编码文本:
Ex:这是我用于将xls文件转换为csv文件的内容。希望它有所帮助
Outputlocation = ....
your_csv_file = open(''.join([Outputlocation,'.csv']), 'wb')
wr = csv.writer(your_csv_file, quoting=csv.QUOTE_ALL)
for rownum in xrange(worksheet.nrows):
wr.writerow([unicode(entry).encode("utf-8") for entry in worksheet.row_values(rownum)])
your_csv_file.close()