你好,我遇到了一个文件对话框功能,我的程序有问题。
首先是我的代码:
def getFileInfo(self):
global logName
logName = QtGui.QFileDialog.getOpenFileName()
return logName
def getFileName(self):
return logName
def compareAction(self):
def process(infile, outfile, keywords):
keys = [[k[0], k[1], 0] for k in keywords]
endk = None
with open(infile, 'rb') as fdin:
with open(outfile, 'ab') as fdout:
fdout.write("<" + words + ">" + "\r\n")
for line in fdin:
if endk is not None:
fdout.write(line)
if line.find(endk) >= 0:
fdout.write("\r\n")
endk = None
else:
for k in keys:
index = line.find(k[0])
if index >= 0:
fdout.write(line[index + len(k[0]):].lstrip())
endk = k[1]
k[2] += 1
if endk is not None:
raise Exception(endk + "Not found before end of file")
return keys
clearOutput = open('test.txt', 'wb')
clearOutput.truncate()
clearOutput.close()
outputText = 'test.txt'
end_token = "[+][+]"
inputFile = logName
start_token = self.serialInputText.toPlainText()
split_start = start_token.split(' ')
for words in split_start:
process(inputFile,outputText,((words + "SHOWALL"),))
fo = open(outputText, "rb")
text = fo.read()
print start_token + '\r\n'
print split_start
print inputFile
好的,所以这段代码的一般想法是从我的PyQt GUI中的TextEdit中获取一些输入文本。然后,将该字符串拆分为可用于“扫描&#39;通过该文件,如果有任何匹配,则将这些匹配打印到另一个文本文档中。
步骤:
This is a list
- &gt; [u'This', u'Is', u'A', u'List']
(由于我的代码使用了sip
,因此列表中有一个u) def process
函数传递它。def getFileInfo(self)
和def GetFileName(Self)
函数发挥作用的地方。 def compareAction(self)
功能。问题
目前,我的问题是在执行步骤6失败的所有步骤后出现此错误。这是我的错误:
Traceback (most recent call last):
File "RETRACTED.py", line 278, in compareAction
process(inputFile,outputText,((words + "SHOWALL"),))
File "RETRACTED.py", line 260, in process
index = line.find(k[0])
UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128)
我不确定为什么会发生这种错误。我一直在寻找类似的问题,但我相信这与我的process
功能有关。我不确定
答案 0 :(得分:1)
该特定错误:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128)
在输入文件中看起来像是(意外的)Byte Order Mark(BOM)的问题。我怀疑日志文件是带有BOM的UTF-8。
尝试将文件打开行更改为:
open(infile, 'rb', encoding='utf-8-sig')
从文件中删除BOM标记。