前言
提示:读取和处理文件经常遇到编码问题:
可以利用标准库来获取文件的编码
使用步骤
1.引入库
代码如下(示例):
import chardet
2.编写函数方便调用
代码如下(示例):
# 获取文件编码
def get_file_encode(file_path):
with open(file_path, 'rb') as f:
return chardet.detect(f.read())['encoding']
3.使用
with open(label_path, 'r', encoding=get_file_encode(label_path)) as f:
label_result = json.load(f)