UnicodeEncodeError: 'gbk' codec can't encode character '\xa0' in position 46:illegal multibyte sequence
in 39 can sequence position character GBK
2023-09-11 14:14:08 时间
一、 最近使用python写入文件时,出现了如下的错误:
但是content的内容是unicode编码,不知道怎么和gbk扯上了关系,对content使用encode()和decode(),用gbk,utf-8,gb2312各种编码解码都没有效果;
在网上查找资料,看到一篇文章关于这个的说法:http://blog.csdn.net/xiaoyi_zhang/article/details/51675099
结论是:
1.‘gbk’ codec can’t encode character :说明是将Unicode字符编码为GBK时候出现了问题,可能是本身Unicode类型的字符中,包含了一些无法转换为GBK编码的一些字符;
2. gbk无法转换'\xa0'字符,所以在转换前需要将“\xa0”替换掉;使用string.replace(u'\xa0', u' ');
我在上述代码中使用:
self.file.write(content.replace(u'\xa0', u''))
结果有效,没有报错;
另外一种方法,在gbk解码时忽略掉不能解码的数据:
self.file.write(content.encode("gbk", 'ignore').decode("gbk", "ignore"))
但是总觉得这种方法是在回避问题,后来突发灵感,这是在文件写入的时候报的错误,而万恶的windows打开文件默认是以“gbk“编码的,可能造成不识别unicode字符,于是做了如下的修改:
self.file = open('biaobai.json', 'w', encoding="utf-8")
self.file.write(content)
结果OK!
相关文章
- G面经prepare: Maximum Subsequence in Another String's Order
- 解决python编码问题报错:'ascii' codec can't encode characters in position 0-15: ordinal not in range(128)
- win7环境下,vagrant,在启动虚拟机的时候报错io.rb:32:in `encode': incomplete "xC8" on GBK (Encoding::InvalidByteSequenceError)
- How to run python interactive in current file's directory in Visual Studio Code? Python路径问题
- cannot open window service on computer '.' in window application
- case when in sql server's stored procedure
- Can't find PHP headers in /usr/include/php
- Word Art In Bash
- Can't locate ExtUtils/MakeMaker.pm in @INC 错误的解决方式
- MySQL 中 You can't specify target table '表名' for update in FROM clause错误解决办法
- 编译内核时报错./include/net/sch_generic.h:535:28: error: inlining failed in call to always_inline 'qdisc_pkt_len': indirect function call with a yet undetermined callee static inline unsigned int qdisc_pkt_
- What's Dead & Exploded in Swift's exception stack?
- python pip使用报错:Fatal error in launcher: Unable to create process using '"'
- webpack遇见的坑:Please install 'webpack-cli' in addition to webpack itself to use the CLI.
- Spring循环依赖报错Bean with name '**' has been injected into other beans [**] in its raw version as part
- Qt error ------ incomplete type 'QApplication' used in nested name specifier
- nacos 报错 Unknown column 'encrypted_data_key' in 'field list'
- python:python2与python3共存时,pip冲突,提示Fatal error in launcher: Unable to create process using '"d:python27python2.exe" "D:Python27Scriptspip2.exe" '
- uwsgi启动Django项目时:unable to load app 0 (mountpoint='') (callable not found or import error) *** no app loaded. going in full dynamic mode ***
- [已解决]报错:UnicodeEncodeError: 'latin-1' codec can't encode characters in position 80-81