我正在使用python 2.7并在我的代码中使用中文字符,所以......
# coding = utf-8
问题是我的代码的一部分,如下所示:
def fileoutput():
global percent_shown
date = str(datetime.datetime.now()).decode('utf-8')
with open("result.txt","a") as datafile:
datafile.write(date+" "+str(percent_shown.get()))
percent_shown是一个包含中文字符的字符串
当我运行它时,我得到:
UnicodeEncodeError:'ascii'编解码器无法编码位置0-2的字符:序数不在范围内(128)
如何解决?感谢
答案 0 :(得分:0)
答案 1 :(得分:0)
根据PEP 263,编码声明必须与正则表达式r"^[ \t\v]*#.*?coding[:=][ \t]*([-_.a-zA-Z0-9]+)"
匹配,因此您需要摆脱编码"之间的空间。和等号:
# coding=utf-8
这个声明告诉python .py
文件本身是utf-8编码的,但不会改变程序的其余部分。如果您正在编写unicode文字但是仍然需要将它们转换为unicde以确保其正常工作,这非常有用。
由于您还没有向我们展示您要打印的内容,因此我发现了一些中文字符。我不知道它们是什么意思......所以我侮辱的任何人都应该知道!
foo = u"学而设" # Good! you've got a unicode string
bar = "学而设" # Bad! you've got a utf-8 encoded string that python
# thinks is ascii
我认为你可以通过一些调整来修复你的程序。首先,不要尝试解码datetime.now()。它只是ascii。它没有改变它的返回类型只是因为你声明了源文件编码。其次,使用codecs
模块打开带有编码的文件(我假设它的utf-8)。现在,由于您正在使用unicode字符串,因此可以将它们直接写入文件。
import codecs
def fileoutput():
date = unicode(datetime.datetime.now())
with codecs.open("result.txt","a", encoding="utf-8") as datafile:
datafile.write(date+" "+percent_shown.get())