Python中使用codecs解决生僻字处理异常('gbk' codec can't encode...)

'gbk' codec can't encode character 'ue863'

python处理文本的时候时常会遇到生僻字出现的处理异常,查了很多资料,发现codecs可以解决这个问题,这里列举一个从excel中读取数据并写入csv中的实例:

#python3.4
import xlrd
import csv
import codecs
data=xlrd.open_workbook("导入.xls")
table=data.sheets()[0]
nrows=table.nrows
ncols=table.ncols
a=list()
for i in range(nrows ):
      a.append(table.row_values(i))
      a[i].append('hello')

with codecs.open('my.csv','w+','utf-8') as csv_file:  
    writer = csv.writer(csv_file)  
    for row in a:  
        writer.writerow(row)

以上代码可以将Excel中的生僻字写入csv。

你可能感兴趣的:(codecs,python3.x)