成都网站建设设计

将想法与焦点和您一起共享

怎么解决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

报错如图:
怎么解决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)

另外有需要云服务器可以了解下创新互联cdcxhl.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


名称栏目:怎么解决Python读取log文件时报错-创新互联
标题链接:http://chengdu.cdxwcx.cn/article/pgsjp.html