学习“笨办法学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