python读取文件编码错误_关于python 读取txt文件出现编码问题:

python 读取txt文件出现编码问题:UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0xba in position 5: invalid start byte 或者 UnicodeDecodeError: ‘gbk’ codec can’t decode byte 0xa7 in position 11144: illegal multibyte sequence等

使用代码:

txt = open('红楼梦.txt','r',encoding = 'utf-8').read()

出现错误:

UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0xba in position 5: invalid start byte

将代码改成:

txt = open('红楼梦.txt','r',encoding = 'gbk').read()

再次报错:

UnicodeDecodeError: ‘gbk’ codec can’t decode byte 0xa7 in position 11144: illegal multibyte sequence

这类错误是txt文件编码问题。

解决方案:打开对应txt文件,找到其右下角对应编码方式,如下图

将其输入至代码"encoding ="后面 替换即可,我这里是ANSI。

最后代码更正如下

txt = open('红楼梦.txt','r',encoding = 'ANSI').read()

修改后没有再出现这类报错。

原文链接:https://blog.csdn.net/qq_42518033/article/details/105263182

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值