首页 > 编程语言 > 详细

Python读取log文件报错“UnicodeDecodeError”

时间:2020-03-08 23:38:11      阅读:101      评论:0      收藏:0      [点我收藏+]
问题描述:

写了一个读取log文件的Python脚本:

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

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

但是在执行时报错:
执行代码报错:

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‘:

# -*- 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 以二进制读模式打开):

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

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

Python读取log文件报错“UnicodeDecodeError”

原文:https://blog.51cto.com/10950710/2476370

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!