Python---serial

本文深入探讨了使用Python进行数据持久化的方法,重点介绍了pickle和json库的应用,通过具体代码实例展示了如何将数据序列化为pickle文件和json格式,以及如何反序列化读取数据。同时,对比了pickle和json在不同场景下的适用性。
import pickle
import pickletools
import json

def pickle1():
	list1={}
	list1['name']='jack'
	list1['age']=22
	with open('data.pickle', mode='wb') as file:
		pickle.dump(list1, file)

def pickle2():
	with open('data.pickle', mode='rb') as file:
		list1=pickle.load(file)
		print(list1)

def pickle4():
	with open('data.pickle', mode='rb') as file:
		pickletools.dis(file)

def pickle3():
	list1={}
	list1['name']='hellen'
	list1['age']=18
	b=pickle.dumps(list1)
	list2=pickle.loads(b)
	print(list2)

def json1():
	list1={}
	list1['name']='cindy'
	list1['age']=29
	with open('data.json', mode='w', encoding='utf-8') as f:
		json.dump(list1, f, indent=2)
'''
1. mode,encoding: json is based on character, so mode should not be byte, encoding should be set
2. indent: one value as one line
3. data type in json and python:
	dictionary--------json: object
	list-----------json:array
	string-------json:string
	integer------json:integer
	True---------json:true
	False--------json:false
	None--------json:null
	float--------json:real number
'''

def json2():
	with open('data.json', mode='r', encoding='utf-8') as f:
		list1 = json.load(f)
		print(list1)

if __name__ == '__main__':
	pickle1()
	pickle2()
	pickle3()
	pickle4()
	json1()
	json2()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值