温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-05-23 14:15:56 来源:亿速云 阅读:661 作者:鸽子 栏目:系统运维

问题描述:

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

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

问题原因:

这是因为日志编码格式和读取日志的解码格式不一致导致的

问题解决:

方法一,读取文件指定“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)

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI