文本文件读写:显示 UnicodeDecodeError: 'gbk' codec can't decode byte 0xad in position 2: illegal multibyte sequence
#代码
textFile = open("7.1.txt","rt")
print(textFile.readline())
textFile.close()
#运行结果
UnicodeDecodeError: 'gbk' codec can't decode byte 0xad in position 2: illegal multibyte sequence
1.初步解决方法:把txt文件中的中文字符用英文表达后运行成功;
2. 指定解码方式:utf-8
textFile = open("7.1.txt","rt", encoding="utf-8")
3.更换为另一个txt文件后成功打开
textFile = open("《哈姆雷特》.txt","rt")
print(textFile.readline())
textFile.close()
根据以上操作怀疑是两个文件的编码格式不一样,于是查看了两个txt的编码格式,打开文本文件——文件——另存为——编码格式,一个是utf-8,另一个是ANSI。说明python语言不指定解码方式,只能直接打开ANSI编码的文件,其他编码方式(utf-16)也不能直接打开。