【问题标题】:Python: Why am I getting a UnicodeDecodeError?Python:为什么我会收到 UnicodeDecodeError?
【发布时间】:2013-01-09 17:03:51
【问题描述】:

我有以下代码使用 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 file-io python-unicode


    【解决方案1】:

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

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

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

    请参阅Python Unicode HOWTO 了解更多信息。

    【讨论】:

    • 我会在哪里添加“b''”
    • @LWH91:首先阅读 HOWTO 以了解 的含义
    • Python 3 有open(fname, mode, encoding='whatever'),Python 2 有codecs.open(fname, mode, encoding='whatever')
    • @JochenRitzel:让我们把重点放在 Python 3 上;无需为 OP 混淆更多的事情。 :-)
    • @MartijnPieters 我读过,明白问题但仍不知道如何解决
    【解决方案2】:

    我对 python 3x 不太熟悉,但下面可能会起作用。

    inputFile = open((x, encoding="utf8"), "r")
    

    【讨论】:

    • 当我尝试得到错误提示时,SyntaxError: non-keyword arg after keyword arg
    【解决方案3】:

    这里有一个类似的问题: Python: Traceback codecs.charmap_decode(input,self.errors,decoding_table)[0]

    但你可能想试试:

     open((x), "r", encoding='UTF8')
    

    【讨论】:

      【解决方案4】:

      非常感谢您提供此解决方案。它对我使用的另一个主题有帮助:

      exec (open ("DIP6.py").read ())
      

      我收到了这个错误,因为我在 DIP6.py 的评论中有这个符号:

       #       ● en première colonne
      

      它适用于:

      exec (open ("DIP6.py", encoding="utf8").read ())
      

      它还解决了一个问题:

      print("été") for example
      

      在 DIP6.py 中

      我明白了:

      été
      

      在控制台中。

      谢谢你:-)。

      【讨论】:

        猜你喜欢
        • 2018-07-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-05
        • 2016-08-21
        • 2014-07-04
        • 2020-06-06
        相关资源
        最近更新 更多