【问题标题】:How to read special characters encoded in UTF-8 in python如何在python中读取以UTF-8编码的特殊字符
【发布时间】:2016-11-28 08:18:30
【问题描述】:

我试图使用 python 从 mysql 数据库中提取一些数据,但是我遇到了特殊字符的问题(数据是 FR、ES、De 和 IT 语言中的字符串)。每当一个单词有一个特殊字符(如重音 áñ 等)时,文件中没有正确编码(我正在使用提取的数据创建一个 csv) 这是我使用的代码

import mysql.connector
if __name__ == '__main__':

    cnx = mysql.connector.connect(user='user', password='psswrd',
                              host='slave',
                              database='DB',
                              buffered=True)
    us_id_list = ['496305']

    f = open('missing_cat_mappings.csv', 'w')
    for (us_id) in us_id_list:
        print us_id
        mapping_cursor = cnx.cursor()
        query = (format(user_id=us_id,))
        success = False
        fails = 0
        while not success:
            try:
                print "try" + str(fails)
                mapping_cursor.execute(query)
                success = True
            except:
                fails += 1
                if fails > 10:
                    raise

        for row in mapping_cursor:
            f.write(str(row) + "\n")

        mapping_cursor.close()
    f.close()

    cnx.close()

我补充说:

#!/usr/bin/python
# vim: set fileencoding=<UTF-8> :

一开始并没有什么不同。

【问题讨论】:

  • 代码中没有指定编码是utf-8,那么python应该怎么知道呢?

标签: python encoding utf-8 mysql-connector


【解决方案1】:

基本上你需要open二进制模式的CSV文件,'wb'不是文本模式'w'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-20
    • 2010-11-25
    • 2014-02-14
    • 2011-02-21
    • 1970-01-01
    • 1970-01-01
    • 2019-07-22
    • 1970-01-01
    相关资源
    最近更新 更多