Python:为什么我得到UnicodeDecodeError?

1 python file-io python-unicode

我有以下代码使用RE搜索文件,如果找到任何匹配项,则将文件移动到不同的目录中.

import os
import gzip
import re
import shutil

def regEx1():
    os.chdir("C:/Users/David/myfiles")
    files = os.listdir(".")
    os.mkdir("C:/Users/David/NewFiles")
    regex_txt = input("Please enter the string your are looking for:")
    for x in (files):
        inputFile = open((x), "r")
        content = inputFile.read()
        inputFile.close()
        regex = re.compile(regex_txt, re.IGNORECASE)
        if re.search(regex, content)is not None:
            shutil.copy(x, "C:/Users/David/NewFiles")
Run Code Online (Sandbox Code Playgroud)

当我运行它时,我收到以下错误消息:

Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
  File "C:\Python33\Lib\encodings\cp1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 367: character maps to <undefined>
Run Code Online (Sandbox Code Playgroud)

请有人解释为什么会出现此消息

Mar*_*ers 9

在python 3中,当您打开文件以便以文本模式(r)读取时,它会将包含的文本解码为unicode.

由于您没有指定用于读取文件的编码,因此locale.getpreferredencoding正在使用平台默认值(from ),在这种情况下失败.

您需要指定可以解码文件内容的编码,或者以二进制模式打开文件(并使用b''正则表达式的字节模式).

有关更多信息,请参阅Python Unicode HOWTO.

  • Python 3有'open(fname,mode,encoding ='whatever')`,Python 2有`codecs.open(fname,mode,encoding ='whatever')` (2认同)