Skip to main content
 首页 » 编程设计

Python:为什么我会收到 UnicodeDecodeError

2025年05月04日9傻小

我有以下代码使用 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") 

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

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> 

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

请您参考如下方法:

在 python 3 中,当您以文本模式 (r) 打开文件进行读取时,它会将包含的文本解码为 un​​icode。

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

您需要指定一种可以解码文件内容的编码,或者改为以二进制模式打开文件(并使用b'' 字节模式作为您的常规表达式)。

参见 Python Unicode HOWTO获取更多信息。