PyQt 中 QFileDialog 的 UnicodeDecodeError

UnicodeDecodeError with QFileDialog in PyQt

您好,我的程序在使用文件对话框功能时遇到问题。

首先是我的代码:

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 中获取一些输入的文本。然后,将该字符串拆分为一个列表,该列表可用于“扫描”整个文件,如果有任何匹配项,则将这些匹配项打印到另一个文本文档中。

步骤:

  1. 用户在 TextEdit 中输入文本
  2. TextEdit 中的文本被存储到 QString 中
  3. QString 有一个 space 作为分隔符,所以我们将每个条目拆分成一个列表。即 This is a list -> [u'This', u'Is', u'A', u'List'] (由于我的代码使用 sip,列表中有一个 u)
  4. 现在我们有了这个 QStringList,我们可以通过我的 def process 函数传递它。
  5. 我们显然需要一个文件来搜索,这就是 def getFileInfo(self)def GetFileName(Self) 函数发挥作用的地方。
  6. 所以在用户输入一些文本后,选择一个文件进行搜索,he/she会按下一个按钮,我们称它为CompareButton,它会执行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 函数有关。我不确定

具体错误:

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