#'charmap'编解码器无法解码位置1148中的字节0x8d [重复]

Posted

技术标签:

【中文标题】#\'charmap\'编解码器无法解码位置1148中的字节0x8d [重复]【英文标题】:#'charmap' codec can't decode byte 0x8d in position 1148 [duplicate]#'charmap'编解码器无法解码位置1148中的字节0x8d [重复] 【发布时间】:2021-05-04 02:00:29 【问题描述】:

我想阅读几个 .text 文档,但出现了一些错误

lyrics = "".join(f.readlines())

错误是:

UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 1148: character maps to <undefined>

我该如何解决它。如果有人修复它会很有帮助。

我的代码功能是:

def read_lyrics():
reg1 = re.compile("\.txt$")
reg2 = re.compile("([0-9]+)\.txt")
reg3 = re.compile(".*_([0-9])\.txt")
reg4 = re.compile("\[.+\]")
reg5 = re.compile("info\.txt")
lyrics_dictionary = 
#iter all directory and load all song(txt file)
for i in os.listdir():
    if os.path.isdir(i):
        for path,sub,items in os.walk(i):
            if any([reg1.findall(item) for item in items]):
                for item in items:
                    if reg5.findall(item):
                        continue
                    if reg3.findall(item):
                        num = ["0"+reg3.findall(item)[0]]
                        name = "_".join(path.split("/") + num)
                    else:
                        name = "_".join(path.split("/") + reg2.findall(item))
                    
                    print("The path is: ", path)
                    print("The item is: ", item)
                    
                    with open(os.path.join(path,item),"r") as f:
                        print("The file path is: ", f)
                        lyrics = "".join(f.readlines()) 
                        
                        lyrics = reg4.subn("",lyrics)[0]
                        lyrics_dictionary[name] = lyrics
return lyrics_dictionary

【问题讨论】:

那么当您尝试将'charmap'+codec+can't+decode+byte+0x8d+in+position+1148 放入搜索引擎,查看the results,并尝试结果中的建议时,发生了什么? 您的open 电话是open(os.path.join(path,item),"r") as f。在 Python 3 中,它会打开一个默认编码为 UTF-8 的文件。但是您收到一条关于charmap 编码的错误消息,这表明您可能正在Python 2 中运行此代码。如果您是,您的print() 调用会将parens 放入输出中,如('The path is', '...')。跨度> 【参考方案1】:

当您使用open() 时,您还使用默认编码。它很可能不适合你。尝试使用类似的东西 - with open(os.path.join(path,item),"r",encoding='utf8') 或者,如果可以,请检查此文件使用的加密是什么。

尝试检查答案this post,其中一个可能会对您有所帮助。

【讨论】:

当问题由这样的现有 Stack Overflow 帖子回答时,请不要添加您自己的答案 - 而是投票以重复关闭问题。

以上是关于#'charmap'编解码器无法解码位置1148中的字节0x8d [重复]的主要内容,如果未能解决你的问题,请参考以下文章

UnicodeEncodeError:“charmap”编解码器无法在位置 28 编码字符“\u2080”:字符映射到 <undefined>

UnicodeEncodeError:“charmap”编解码器无法在位置 1087 编码字符“\u011f”:字符映射到 <undefined>

Pipreqs:UnicodeDecodeError:'charmap'编解码器无法解码位置 1206 中的字节 0x98:字符映射到 <undefined>

UnicodeDecodeError:'charmap'编解码器无法解码位置Y中的字节X:字符映射到

UnicodeDecodeError:“charmap”编解码器无法解码位置 2310 中的字节 0x81:字符映射到 <undefined>

如何修复''UnicodeDecodeError:'charmap'编解码器无法解码位置29815中的字节0x9d:字符映射到<undefined>''?