首页 > 解决方案 > python文件写入显示UnicodeEncodeError的错误

问题描述

我需要制作 cp932(它已扩展shift-jis

UnicodeEncodeError: 'cp932' codec can't encode character '\u270c' in position 0: illegal multibyte sequence

    import codecs
    mytext = '\u270c'
    with codecs.open(path,mode='w',encoding='cp932') as f:
        mytext.encode('cp932',"ignore")
        f.write(mytext)
    exit()

我只是简化了mytext这篇文章。

我认为这个字符通过忽略 flg 的编码。

但是,write显示错误。

有没有办法解决这个问题??

标签: pythonutf-8encodeshift-jis

解决方案


\是 cp932 中的功能符号。所以,如果你想编码\,你应该\\
在你的情况下使用:

import codecs
mytext = '\\u270c'
with codecs.open(path,mode='w',encoding='cp932') as f:
    mytext.encode('cp932',"ignore")
    f.write(mytext)
exit()

推荐阅读