(常用)Python 数据保存与读取(Pickle,Json)

#pickle保存与读取
def save_pickle_data(save_data_dir, save_data, dataname):
    # 保存数据集
    with open(save_data_dir + "/" + dataname + ".pickle", "wb") as handle:
        # pickle.dump(save_data, handle)
        pickle.dump(save_data, handle, protocol=pickle.HIGHEST_PROTOCOL)
    handle.close()


def read_pickle_data(save_data_dir, dataname):
    with open(save_data_dir + "/" + dataname + ".pickle", 'rb') as handle:
        read_data = pickle.load(handle)
    handle.close()
    return read_data
#JSON格式数据
def read_json_data(save_data_dir, dataname):
    with open(save_data_dir + "/" + dataname + ".json", 'rb') as handle:
        read_data = json.load(handle)
    handle.close()
    return read_data


def save_json_data(save_data_dir, json_dict, dataname):
    #result = json.dumps(json_dict, indent=4)
    #print(result)

    with open(save_data_dir + "/" + dataname + ".json", 'w') as handle:
        json.dump(json_dict, handle, indent=4)
    handle.close()


def save_json_data_ensure_ascii(save_data_dir, json_dict, dataname):
    # result = json.dumps(json_dict, indent=4)
    # print(result)

    with open(save_data_dir + "/" + dataname + ".json", 'w',encoding="utf-8") as handle:
        json.dump(json_dict, handle, indent=4,ensure_ascii=False)
    handle.close()

#按行读取
def read_json_data(save_data_dir):
    read_data = []
    with open(save_data_dir, 'r') as f:
        # read_data = json.load(handle, cls=MyEncoder)
        for jsonobj in f:
            try:
                dataDic = json.loads(jsonobj)
                read_data.append(dataDic)
            except:
                print("#Error#", str(jsonobj))

    return read_data
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值