yuandiyuandi123 发表于 2018-6-9 21:57:37

关于编码格式异常的问题 UnicodeEncodeError

本帖最后由 yuandiyuandi123 于 2018-6-9 23:04 编辑

import time
class MyDes:
   def __init__(self,value,string):
          self.value = value
          self.string = string

   def __get__(self,instance,owner):
          f = open("/Users/yuandi/Downloads/python/py文件夹/record.rtf",'a')
          f.write("%s变量于北京时间 %s 被读取,%s = %s"%(self.string,time.localtime(time.time()),self.string,self.value))
          f.close()
          return self.value

   def __set__(self,instance,value):
          f = open("/Users/yuandi/Downloads/python/py文件夹/record.rtf",'a')
          self.value = value
          f.write("%s变量于北京时间 %s 被修改,%s = %s"%(self.string,time.localtime(time.time()),self.string,self.value))
          f.close()

====================================上面的代码都不重要=============================================

>>> class Test:
        x = MyDes(10,"x")
        y = MyDes(8.8,"y")

       
>>> test = Test()
=====================================问题在这里==================================================
>>> test.x
Traceback (most recent call last):
File "<pyshell#168>", line 1, in <module>
    test.x
File "/Users/yuandi/Downloads/python/py文件夹/MyDes_save.py", line 9, in __get__
    f.write("%s变量于北京时间 %s 被读取,%s = %s"%(self.string,time.localtime(time.time()),self.string,self.value))
UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-7: ordinal not in range(128)




试了一下,只要使用mac系统,向文件中写入中文(rtf或者txt),都会出现这个问题
使用的是python3.6   
如何能解决这个异常呢 ?

第四时空 发表于 2018-6-9 23:33:13

可能你打开文件的时候应该制定一下文件编码,open(xxx,encoding="utf-8")

yuandiyuandi123 发表于 2018-6-10 01:39:28

第四时空 发表于 2018-6-9 23:33
可能你打开文件的时候应该制定一下文件编码,open(xxx,encoding="utf-8")

试过了 还是不行
页: [1]
查看完整版本: 关于编码格式异常的问题 UnicodeEncodeError