Get the App
SLTechnology News&Howtos  ›  Servers  › 

How to solve the error of reading log files by Python

Shulou Source: shulou.com Published: 2022-06-03 06:00:02 09月12日 Update

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)

Tags: File problem utf-8 method log format times consistency binary code reason is in mode code script this is as shown in the figure Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info Microsoft Apple MariaDB vpn