相关疑难解决方法(0)

使用Python读取UTF8 CSV文件

我正在尝试使用Python(只有法语和/或西班牙语字符)读取带有重音字符的CSV文件.基于csvreader的Python 2.5文档(http://docs.python.org/library/csv.html),我提出了以下代码来读取CSV文件,因为csvreader仅支持ASCII.

def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs):
    # csv.py doesn't do Unicode; encode temporarily as UTF-8:
    csv_reader = csv.reader(utf_8_encoder(unicode_csv_data),
                            dialect=dialect, **kwargs)
    for row in csv_reader:
        # decode UTF-8 back to Unicode, cell by cell:
        yield [unicode(cell, 'utf-8') for cell in row]

def utf_8_encoder(unicode_csv_data):
    for line in unicode_csv_data:
        yield line.encode('utf-8')

filename = 'output.csv'
reader = unicode_csv_reader(open(filename))
try:
    products = []
    for field1, field2, field3 in reader:
        ...
Run Code Online (Sandbox Code Playgroud)

以下是我试图阅读的CSV文件的摘录:

0665000FS10120684,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) …
Run Code Online (Sandbox Code Playgroud)

python csv utf-8 character-encoding

90
推荐指数
4
解决办法
18万
查看次数

标签 统计

character-encoding ×1

csv ×1

python ×1

utf-8 ×1