Python: file: encode: ‘gbk‘ codec can‘t encode character ‘\xe5‘ in position

错误

response = requests.get(url, timeout=5) # 请求一个网页

with open('response.txt', 'w') as file: # 打开一个文件

file.write(response.text) # 向文件写入response

提示错:

UnicodeEncodeError: 'gbk' codec can't encode character '\xe5' in position 520: illegal multibyte sequence

原因

这个是因为文件打开使用的编码方式是gbk,是open默认的,在response.text里有gbkencode不了的编码。导致错误。如果换成utf-8,倒是可以输出到文件:

with open('response.txt', 'w', encoding='utf-8') as file:

修改这一句,可以绕过这个错误,但是,打开网页出现乱码。

本地的默认设置是gbk。

cpp 复制代码
>>> import locale
>>> print(locale.getdefaultlocale())
('zh_CN', 'cp936')

Doc/library/codecs.rst

cpp 复制代码
| gbk             | 936, cp936, ms936              | Unified Chinese                |

从网上搜了一下,response自带编码方式,可以查阅。

cpp 复制代码
>>> print(response.encoding)
ISO-8859-1

最后改成ISO-8859-1就好了。

相关推荐
早起CaiCai3 分钟前
【Pytorch 实践1】手写数字
人工智能·pytorch·python
周杰伦的稻香10 分钟前
Go + Redis:本地部署高性能图片主色调提取服务
开发语言·redis·golang
吴梓穆14 分钟前
Python 语法基础 函数
开发语言·python
不负岁月无痕17 分钟前
C++ 模板核心内容与高频面试题汇总
java·开发语言·c++
Kobebryant-Manba22 分钟前
学习文本处理
开发语言·python
m0_6174939427 分钟前
PaddleOCR报错:OneDnnContext does not have the input Filter 解决方案汇总
python
李可以量化29 分钟前
量化迅投 QMT vs 聚宽 (JoinQuant)全面分析
python·量化·qmt·ptrade·聚宽
福大大架构师每日一题40 分钟前
2026年6月TIOBE编程语言排行榜,Go语言排名第13,Rust语言排名12。关于Rust已进入平台期的报道似乎为时过早。
开发语言·golang·rust
无限进步_43 分钟前
从零实现一个迷你Shell——深入理解Linux命令行解释器
linux·运维·服务器·开发语言·c++·chrome
旅僧44 分钟前
运行UMI镜像
python