UnicodeDecodeError:“cp932”编解码器无法解码字节 0xfc

Che*_*n.B 3 python character-encoding file-handling python-3.x

import os

for root, dirs, files in os.walk('Path'):
     for file in files:
         if file.endswith('.c'):
             with open(os.path.join(root, file)) as f:
                    for line in f:
                        if 'word' in line:
                            print(line)
Run Code Online (Sandbox Code Playgroud)

得到错误

UnicodeDecodeError:“cp932”编解码器无法解码位置 6616 中的字节 0xfc:非法多字节序列

我认为文件需要shift jis编码。我可以只在开始时设置编码吗?我尝试使用 open(os.path.join(root, file),'r',encoding='cp932') 设置为 f: 但遇到了相同的错误

小智 6

您可以传递errors='ignore',但请确保检查文件的编码是什么。

open(os.path.join(root, file),'r', encoding='cp932', errors='ignore')
Run Code Online (Sandbox Code Playgroud)


小智 5

在这里结束是因为我遇到了同样的错误。

我刚刚学习,幸运的是我找到了解决方案。

如果它说:

UnicodeDecodeError:“cp932”编解码器无法解码

这意味着您使用的文件采用 cp932 编码,因此您实际上需要更改编码。

就我而言,我试图读取以 UTF-8 编码的文件,因此解决方案是在打开文件时包含该文件:

open("file.txt","r",encoding='utf-8')
Run Code Online (Sandbox Code Playgroud)

我希望这对因同样错误而来到这里的任何人有所帮助。