python文件写入显示UnicodeEncodeError错误

I need to make the cp932 (it is expanded 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()

I just simplify the mytext for this article.

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

However, write shows the error.

有什么办法解决这个问题?

评论
  • 浅陌初心
    浅陌初心 回复

    \ is functional symbol in cp932. So, If you want to encode \ you should use the \\
    in your case :

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