Python read log file error "UnicodeDecodeError"

Problem Description:

I wrote a Python script reads the log file:

# -*- coding:utf-8 -*-
import os
import numpy as np
file = 'D:\pythonfile\test.log'

for line in open("test.log","r"):
    print(line)

However, an error in the execution:
executing code error:

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

Error Figure:
Python read log file error "UnicodeDecodeError"

problem causes:

This is because the encoding format and decoding format reading log log caused by the inconsistency

problem solved:

A method, reads the file specified "encoding = 'UTF-8':

# -*- 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)

The second method to read the file specified rb (rb opened in binary read mode):

# -*- coding:utf-8 -*-
import os
import numpy as np
file = 'D:\pythonfile\test.log'

# for line in open("test.log","rb"):
    print(line)

Guess you like

Origin blog.51cto.com/10950710/2476370