我正在尝试创建一个打印到命令提示符和文件的函数.我使用以下代码获得编码/解码错误:
import os
def pas(stringToProcess): #printAndSave
print stringToProcess
try: f = open('file', 'a')
except: f = open('file', 'wb')
print >> f, stringToProcess
f.close()
all = {u'title': u'Pi\xf1ata', u'albumname': u'New Clear War {EP}', u'artistname': u'Montgomery'}
pas(all['title'])
我得到以下输出:
Piñata
Traceback (most recent call last):
File "new.py", line 17, in <module>
pas(all['title'])
File "new.py", line 11, in pas
print >> f, stringToProcess
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 2: ordinal not in range(128)
我已经尝试了所有的编码()/ decode()排列,我可以从这里的类似答案想象,但没有成功.如何解决这个错误?
最佳答案 正如有人评论的那样,您可能只需要指定在编写字符串时使用的编解码器.例如,这对我有用:
def pas(s):
print(s)
with open("file", "at") as f:
f.write("%s\n" % s.encode("utf-8"))
pas(u'Pi\xf1ata')
pas(u'Pi\xf1ata')
如您所见,我专门以追加/文本模式打开文件.如果该文件不存在,则将创建该文件.我也使用而不是你的try-except方法.这只是我喜欢的风格.
正如Bhargav所说,您也可以设置默认编码.这一切都取决于你的程序需要多少控制,两种方式都很好.