UnicodeEncodeError: 'gbk' codec can't encode character '\xa0' in position 46:illegal multibyte .....
使用python从mongodb获取数据,并打包成json格式时,出错。转载自https://www.cnblogs.com/cwp-bg/p/7835434.html
源代码如:
json_str = json.dumps(data, indent=4, cls=DateEncoder, ensure_ascii=False)
with open('G:/ALL_NEWS/ALL_Belta/{}2022.json'.format(COLLECTION_NAME), 'w') as json_file:
json_file.write(json_str)
使用ensure_ascii=False,还是出错。当源数据为俄文,报UnicodeEncodeError: ‘gbk’ codec can’t encode character ‘\xa0’ in position 46:illegal multibyte …
这是在文件写入的时候报的错误,而万恶的windows打开文件默认是以“gbk“编码的,将代码修改成指定utf-8编码格式打开文件
json_str = json.dumps(data, indent=4, cls=DateEncoder, ensure_ascii=False)
with open('G:/ALL_NEWS/ALL_Belta/{}2022.json'.format(COLLECTION_NAME), 'w', encoding="utf-8") as json_file:
json_file.write(json_str)