How to solve the error of reading log files by Python
Problem description:
Write a Python script to read the log file:
#-*-coding:utf-8-*-import osimport numpy as npfile ='D:\ pythonfile\ test.log'for line in open ("test.log", "r"): print (line)
But in the execution of the Times error:
Execute code to report an error:
Traceback (most recent call last): File "D:/pythonfile/my-test225.py", line 8, in for line in open ("test.log", "r"): UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 6946: illegal multibyte sequenceProcess finished with exit code 1
The error is reported as shown in the picture:
The cause of the problem:
This is due to the inconsistency between the log encoding format and the decoding format for reading the log.
Problem solving:
Method 1, read the file to specify "encoding='UTF-8':"
#-*-coding:utf-8-*-import osimport numpy as npfile ='D:\ pythonfile\ test.log'for line in open ("test.log", "r", encoding='UTF-8'): print (line)
Method 2, read the file to specify rb (rb is opened in binary read mode):
#-*-coding:utf-8-*-import osimport numpy as npfile ='D:\ pythonfile\ test.log'# for line in open ("test.log", "rb"): print (line)