读文件时出现这个错误 '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



免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM