python 学习之FAQ:文档内容写入报错

2017.3.29 FAQ

1、 文档内容写入报错

  使用with open() as file: 写入文档时,出现'\xa9'特殊字符写入报错,通过print('\xa9')打印输出“©”。

>>> print('\xa9')
©

    (1)源码内容

def downloadText(_text):
    with open('text.txt','w') as file:
        file.write(_text)
        file.close()

  (2)报错信息

UnicodeEncodeError: 'gbk' codec can't encode character '\xa9' in position 3011: illegal multibyte sequence

  (3)报错截图

  

  (4) 解决方法

  最后在请教学习群中的同学,给出了解决建议,直接在写入文档时指定明确的编码格式:encoding = 'utf-8',修改后的编码内容如下。

def downloadText(_text):
    with open('text.txt','w',encoding = 'utf-8') as file:
        file.write(_text)
        file.close()

 

posted @ 2017-03-29 10:18  myles007  阅读(328)  评论(0编辑  收藏  举报