学习“笨办法学Python3” ex16遇到的问题_报错:UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0x80 in position 8...

学习“笨办法学Python3” ex16遇到的问题_打开内容为中文的txt文件时报错

一、当执行如下代码时,报错:UnicodeDecodeError: ‘gbk’ codec can’t decode byte 0x80 in position 8: illegal multibyte sequence

print("Now,we second thing is copy the file1 to the file2")
print("Then,we open the file2 and check it")
file2 = input(">>")
type4 = open(file2)
type5 = type4.read()
type6 = print(type5) 

错误提示:

Traceback (most recent call last):
  File "D:/Users/myself/PycharmProjects/pylearn/ex1-21_Summary.py", line 227, in <module>
    type5 = type4.read()
UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 8: illegal multibyte sequence

二、原因是txt文件有中文内容,但是代码中没有encoding=“utf-8”。
三、修改代码为:

rint("Now,we second thing is copy the file1 to the file2")
print("Then,we open the file2 and check it")
file2 = input(">>")
type4 = open(file2, encoding='UTF-8')
type5 = type4.read()
type6 = print(type5) 

四、代码修改成功

Process finished with exit code 0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值