Python:为什么我会得到一个UnicodeDecodeError?
我有下面的代码,使用RE搜索文件,如果找到任何匹配项,它会将文件移动到另一个目录中Python:为什么我会得到一个UnicodeDecodeError?,python,file-io,python-unicode,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
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打开一个文件进行读取时,它会将包含的文本解码为unicode 由于您没有指定读取文件所使用的编码,因此使用的是平台默认值,在本例中失败 您需要指定可以解码文件内容的编码,或者改为以二进制模式打开文件,并对正则表达式使用b字节模式
有关更多信息,请参阅。在python 3中,当您以文本模式r打开一个文件进行读取时,它会将包含的文本解码为unicode 由于您没有指定读取文件所使用的编码,因此使用的是平台默认值,在本例中失败 您需要指定可以解码文件内容的编码,或者改为以二进制模式打开文件,并对正则表达式使用b字节模式
有关更多信息,请参阅。我对python 3x不太熟悉,但下面的内容可能会有用
inputFile = open((x, encoding="utf8"), "r")
我对python3x不太熟悉,但下面的内容可能会有用
inputFile = open((x, encoding="utf8"), "r")
这里有一个类似的问题: 但您可能想尝试:
open((x), "r", encoding='UTF8')
这里有一个类似的问题: 但您可能想尝试:
open((x), "r", encoding='UTF8')
非常感谢您提供此解决方案。它对我的另一个主题有帮助,我使用:
exec (open ("DIP6.py").read ())
我得到这个错误是因为我在DIP6.py的注释中有一个符号:
# ● en première colonne
它适用于以下情况:
exec (open ("DIP6.py", encoding="utf8").read ())
它还解决了以下问题:
print("été") for example
在6.py中
我得到:
été
在控制台中
谢谢:-.非常感谢您提供此解决方案。它对我的另一个主题有帮助,我使用:
exec (open ("DIP6.py").read ())
我得到这个错误是因为我在DIP6.py的注释中有一个符号:
# ● en première colonne
它适用于以下情况:
exec (open ("DIP6.py", encoding="utf8").read ())
它还解决了以下问题:
print("été") for example
在6.py中
我得到:
été
在控制台中
谢谢:-.我应该在哪里添加b@LWH91:首先阅读HOWTO以了解其含义。Python 3有openfname,mode,encoding='whatever',Python 2有编解码器。openfname,mode,encoding='whatever'@JochenRitzel:让我们把重点放在Python 3上;无需再为OP混淆更多内容:-@MartijnPieters我已经读过了,理解了问题,但仍然不知道如何解决问题我应该在哪里添加b@LWH91:首先阅读HOWTO以了解其含义。Python 3有openfname,mode,encoding='which',Python 2有编解码器。openfname,mode,encoding='whatever'@JochenRitzel:让我们把重点放在Python 3上;无需为OP混淆更多内容:-@MartijnPieters我读过,了解问题,但仍然不知道如何解决当我尝试时,我得到一个错误,在关键字arg之后说SyntaxError:non-keyword arg当我尝试时,我得到一个错误,在关键字arg之后说SyntaxError:non-keyword arg