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)
得到错误
UnicodeDecodeError:“cp932”编解码器无法解码位置 6616 中的字节 0xfc:非法多字节序列
我认为文件需要 shift jis 编码。我可以只在开始时设置编码吗?我尝试将 open(os.path.join(root, file),‘r’,encoding=‘cp932’) 设置为 f: 但得到了同样的错误
原文由 Chetan.B 发布,翻译遵循 CC BY-SA 4.0 许可协议
你可以传递 errors=‘ignore’,但一定要检查你的文件的编码是什么。