PyQt中带有QFileDialog的UnicodeDecodeError

时间:2015-09-08 14:51:25

标签: python file pyqt filedialog

你好,我遇到了一个文件对话框功能,我的程序有问题。

首先是我的代码:

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;通过该文件,如果有任何匹配,则将这些匹配打印到另一个文本文档中。

步骤:

  1. 用户将文本输入TextEdit
  2. TextEdit中的文本存储在QString
  3. 那个QString有一个空格作为分隔符,所以我们将每个条目分成一个列表。即This is a list - &gt; [u'This', u'Is', u'A', u'List'] (由于我的代码使用了sip,因此列表中有一个u)
  4. 现在我们有了这个QStringList,我们可以通过我的def process函数传递它。
  5. 我们需要一个文件来搜索显然,这是def getFileInfo(self)def GetFileName(Self)函数发挥作用的地方。
  6. 因此,在用户输入了一些文本,选择要搜索的文件后,他/她将按下一个按钮,我们称之为CompareButton,它将执行def compareAction(self)功能。
  7. 问题

    目前,我的问题是在执行步骤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功能有关。我不确定

1 个答案:

答案 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标记。