【发布时间】:2012-04-26 16:06:20
【问题描述】:
我写了下面的代码来将内容写入文件,
with codecs.open(name,"a","utf8") as myfile:
myfile.write(str(eachrecord[1]).encode('utf8'))
myfile.write(" ")
myfile.write(str(eachrecord[0]).encode('utf8'))
myfile.write("\n")`
上面的代码在编写 uni-code 字符时不能正常工作......即使我正在使用编解码器并进行编码。我不断收到错误
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe1' in position 6: ordinal not in range(128)
谁能看出我哪里做错了?
编辑:
with codecs.open(name,"a","utf8") as myfile:
myfile.write(unicode(eachrecord[1]))
myfile.write(" ")
myfile.write(unicode(eachrecord[0]))
myfile.write("\n")
这行得通..感谢所有快速的 cmets 和答案..这真的很有帮助..直到你们告诉我,我才意识到 python 有 'unicode' 选项
【问题讨论】:
-
eachrecord[1]是什么类型?我猜str弄得一团糟,请改用unicode。 -
而且我认为您甚至不必对 unicode 字符串进行编码,因为使用编解码器打开的文件应该可以处理它。
-
每个记录[1] 可以是字符串或数字
-
TypeError: coercing to Unicode: need string or buffer, int found..关于如何解决这个问题的任何建议