python如何读取log文件_怎么解决Python读取log文件时报错

怎么解决Python读取log文件时报错

发布时间:2020-05-23 14:15:56

来源:亿速云

阅读:157

作者:鸽子

问题描述:

写了一个读取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

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)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值