怎么解决Python读取log文件时报错
问题描述:
写了一个读取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)
网页标题:怎么解决Python读取log文件时报错
路径分享:http://ybzwz.com/article/ipjgcd.html