写了一个读取log文件的Python脚本:python
# -*- coding:utf-8 -*- import os import numpy as np file = 'D:\pythonfile\test.log' for line in open("test.log","r"): print(line)
可是在执行时报错:
执行代码报错:ide
Traceback (most recent call last): File "D:/pythonfile/my-test225.py", line 8, in <module> for line in open("test.log","r"): UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 6946: illegal multibyte sequence Process finished with exit code 1
报错如图:编码
这是由于日志编码格式和读取日志的解码格式不一致致使的日志
方法一,读取文件指定“encoding='UTF-8':code
# -*- coding:utf-8 -*- import os import numpy as np file = 'D:\pythonfile\test.log' for line in open("test.log","r",encoding='UTF-8'): print(line)
方法二,读取文件指定rb(rb 以二进制读模式打开):utf-8
# -*- coding:utf-8 -*- import os import numpy as np file = 'D:\pythonfile\test.log' # for line in open("test.log","rb"): print(line)