【发布时间】:2018-02-01 23:07:03
【问题描述】:
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:非法多字节序列
我认为文件需要移位 jis 编码。 我可以只在开始时设置编码吗? 我试过设置 使用 open(os.path.join(root, file),'r',encoding='cp932') 作为 f: 但同样的错误
【问题讨论】:
-
您能否添加完整的堆栈跟踪,以查看异常是在“print(line)”还是“for line in f”上引发的?您可能必须以二进制模式打开文件,因为您不知道所有文件的编码。
标签: python python-3.x character-encoding file-handling