python读取文件内容报错,应该是编码问题,求解答
#-*-coding:cp936-*-importosdeffilters():#获取当前路径path=os.getcwd()LogPath=path+"\Monkeyl...
#-*- coding:cp936 -*-
import os
def filters():
#获取当前路径
path = os.getcwd()
LogPath =path+"\Monkeylogcat.log"
LogLine = open(LogPath)
Results = {}
Keywords = "E/AndroidRuntime"
Mobo = "mobogenie"
for line in LogLine:
if (Keywords in line) and (Mobo in line):
Results[line] = 1
if line in Results.keys():
Results[line]+=1
LogLine.close()
Output = open('result.txt', 'w')
Output.write("Key\tnum\n")
keys = Results.keys()
for key in keys:
Output.write(key)
Output.write("\t")
Output.write(Results[key])
Output.write("\n")
Output.close()
if __name__ == "__main__":
filters()
报错:UnicodeDecodeError: 'gbk' codec can't decode bytes in position 7299-7300: illegal multibyte sequence 展开
import os
def filters():
#获取当前路径
path = os.getcwd()
LogPath =path+"\Monkeylogcat.log"
LogLine = open(LogPath)
Results = {}
Keywords = "E/AndroidRuntime"
Mobo = "mobogenie"
for line in LogLine:
if (Keywords in line) and (Mobo in line):
Results[line] = 1
if line in Results.keys():
Results[line]+=1
LogLine.close()
Output = open('result.txt', 'w')
Output.write("Key\tnum\n")
keys = Results.keys()
for key in keys:
Output.write(key)
Output.write("\t")
Output.write(Results[key])
Output.write("\n")
Output.close()
if __name__ == "__main__":
filters()
报错:UnicodeDecodeError: 'gbk' codec can't decode bytes in position 7299-7300: illegal multibyte sequence 展开
3个回答
展开全部
建议用codecs.open替代open; 若LogPath文件是以utf-8编码格式保存的:
LogLine = open(LogPath) ==> LogLine = codecs.open(LogPath, 'r', 'utf-8')
LogLine = open(LogPath) ==> LogLine = codecs.open(LogPath, 'r', 'utf-8')
追问
LogLine = codecs.open(LogPath, 'r', 'utf-8')
NameError: global name 'codecs' is not defined
提示这个 错误
LogLine = open(LogPath, 'r', 'utf-8')
TypeError: an integer is required
咋回事截,以前读文本文件从来没有过这样的问题
追答
codecs是python的一个模块,你在使用前需要先import
#-*- coding:cp936 -*-
import os
import codecs
..
展开全部
类型不匹配
Output.write(Results[key])//这里Results[key]为int类型,加一个类型转换str(Results[key])
Output.write(Results[key])//这里Results[key]为int类型,加一个类型转换str(Results[key])
追问
恩恩,那块是有点问题,可是这个报错是读文件的时候出现的,不是写文件的时候出的
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
import os,sys
reload(sys)
sys.setdefaultencoding('utf-8')
在上面加上这几句吧
reload(sys)
sys.setdefaultencoding('utf-8')
在上面加上这几句吧
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询