python中open函数打开.py文件,编码错误

问题:

  • python中open函数打开.py文件,会报错
>>> file=open('example.py','r')
>>> for line in file:print(line)
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'gbk' codec can't decode byte 0xae in position 331: illegal multibyte sequence

原因:

  • open函数默认的编码格式是基于系统的,中文windows默认gbk

解决方案:

  • encoding属性设置为‘utf-8’
>>> file=open('example.py','r',encoding='utf-8')

猜你喜欢

转载自blog.csdn.net/yangwenwu11514/article/details/85222937