读文件时出现这个错误 'utf-8' codec can't decode byte 0xba in position 21: invalid start byte

''' file2 文件内容:


很任性
when
i
was
young

'''


源代码:
f = open("file2",'r',encoding="utf-8")
print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())


错误提示:
D:\python\python.exe D:/pythonWork/day2/file-op.py
Traceback (most recent call last):
  File "D:/pythonWork/day2/file-op.py", line 10, in <module>
    print(f.readline())
  File "D:\python\lib\codecs.py", line 321, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xba in position 21: invalid start byte

修改之后代码:
f = open("file2",'r',encoding="gbk")
print(f.readline())    
print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())


执行结果:

很任性
when
i
was
young

Process finished with exit code 0


posted @ 2019-07-08 21:14  梦幻轩  阅读(28207)  评论(1编辑  收藏  举报