pickle json 保存python类型数据

pickle 模块可以保存任意类型的python数据,包括类变量,数组,字符等等。
用法也很简单。
一个简单的代码如下:

import pickle

class Test(object):
    
    test1 = 'test'
    

instance = Test()

instance.test1 = 'This is a test'

with open('test.pkl', 'wb') as f:
    data = pickle.dumps(instance)
    f.write(data)
    
    
with open('./test.pkl', 'rb') as f:

    data = f.read()
    instance_read = pickle.loads(data)    
    

print(instance_read.test1)

输出:

This is a test

但是pickle模块本身并不安全,只有当数据来源来源可靠时才可以使用,避免使用处理来源不可靠,或者被篡改的数据。一般情况下建议使用json模块,但是json模块只支持python经典的数据结构,像类变量这种无法使用json保存。
json的使用也非常简单。例子如下:

import json

test = {'test1': 1, 'test2': 2}

with open('test.json', 'w') as f:
    data = json.dumps(test)
    f.write(data)
    
with open('test.json', 'r') as f:

    data = f.read()
    test_read = json.loads(data)    
   
print(test_read)

输出:

{'test1': 1, 'test2': 2}

禁止转载

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值