Python文件自适应文件编码
背景:对某APP抓包解析后,提取的json文件不能直接使用loads读取,且有部分一个json文件存在两行json数据的情况
1、json文件编码格式自适应
check_charset 函数
import chardet
def check_charset(file_path):
with open(file_path, "rb") as f:
data = f.read(4)
charset = chardet.detect(data)['encoding']
return charset
使用
open(file_path, encoding=check_charset(file_path))
2、一个json文件存在两个json数据
with open(file_path, encoding=check_charset(file_path)) as f:
try:
data_arr = f.read().split('\n\n\n')
for data in data_arr:
json_data = json.loads(data)