Python 2.7:在写入文件时,“ ascii”编解码器无法编码字符u'xe9'错误 [英] Python 2.7: 'ascii' codec can't encode character u'\xe9' error while writing in file
问题描述
我知道这个问题已经被问了好几次了,但是不知何故我没有得到结果。
I know this question have been asked various time but somehow I am not getting results.
我正在从包含字符串Elzéar。在读入CSV文件时,它会给出问题标题中提到的错误。
I am fetching data from web which contains a string Elzéar. While going to read in CSV file it gives error which mentioned in question title.
在生成数据时,我做了以下操作:
While producing data I did following:
address = str(address).strip()
address = address.encode('utf8')
return name+','+address+','+city+','+state+','+phone+','+fax+','+pumps+','+parking+','+general+','+entertainment+','+fuel+','+resturants+','+services+','+technology+','+fuel_cards+','+credit_cards+','+permits+','+money_services+','+security+','+medical+','+longit+','+latit
并将其写为:
with open('records.csv', 'a') as csv_file:
print(type(data)) #prints <unicode>
data = data.encode('utf8')
csv_file.write(id+','+data+'\n')
status = 'OK'
the_file.write(ts+'\t'+url+'\t'+status+'\n')
产生错误,例如:
'ascii'编解码器无法在位置55编码字符u'\xe9':序号
不在范围内(128)
'ascii' codec can't encode character u'\xe9' in position 55: ordinal not in range(128)
推荐答案
您可以尝试类似(python2.7) :
You could try something like (python2.7):
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import codecs
...
with codecs.open('records.csv', 'a', encoding="utf8") as csv_file:
print(type(data)) #prints <unicode>
# because data is unicode
csv_file.write(unicode(id)+u','+data+u'\n')
status = u'OK'
the_file.write(unicode(ts, encoding="utf8")+u'\t'+unicode(url, encoding="utf8")+u'\t'+status+u'\n')
主要思想是尽可能多地使用unicode并在输出时返回str(最好不要在str上操作)。
The main idea is to work with unicode as much as possible and return str when outputing (better do not operate over str).
这篇关于Python 2.7:在写入文件时,“ ascii”编解码器无法编码字符u'xe9'错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!