python3.x 基础四:json与pickple
Posted 不懂ABAP的python不是好basis
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python3.x 基础四:json与pickple相关的知识,希望对你有一定的参考价值。
- 每次打开一个文件,只dump1次
- json.dump(dump的内容,文件句柄)
- json.load(文件句柄)
- json可以处理列表/字典/字符串等简单数据类型,但是不能处理复杂的数据类型,如函数的内存地址
- 不同语言间都可以用json文件
import json dict1={‘name‘:‘alex‘,‘age‘:22,‘salary‘:1000} print(‘dict is %s\ndumping dict to file...‘ % (dict1)) fd = open(‘fd.txt‘,‘w‘,encoding=‘utf-8‘) # with open(‘fd.txt‘,‘w‘,encoding=‘utf-8‘) as fd: # json.dump(dict1,fd) dict2={‘name‘:‘oldboy‘,‘age‘:32,‘salary‘:2000} # with open(‘fd.txt‘,‘w‘,encoding=‘utf-8‘) as fd: # json.dump(dict2,fd) json.dump(dict1,fd) fd.close() # json.dump(dict2,fd) fd = open(‘fd.txt‘,‘r‘,encoding=‘utf-8‘) print(‘load content from file...‘) print(json.load(fd)) fd.close()
output:
dict is {‘age‘: 22, ‘salary‘: 1000, ‘name‘: ‘alex‘}
dumping dict to file...
load content from file...
{‘age‘: 22, ‘salary‘: 1000, ‘name‘: ‘alex‘}
dumping dict to file...
import json dict1={} def func(): print(‘in the func‘) dict1[‘name‘]=func fd = open(‘fdw.txt‘,‘w‘,encoding=‘utf-8‘) print(‘dumping dict to file...‘ % (dict1)) json.dumps(dict1,fd) fd.close()
error:
TypeError: <function func at 0x7f0828c68488> is not JSON serializable
- pickle能处理python所有的数据类型
import pickle dict1={} def func(): print(‘in the func‘) dict1[‘name‘]=func fd = open(‘fdw.txt‘,‘wb‘) print(‘dumping dict to file... %s‘ % (dict1)) pickle.dump(dict1,fd) fd.close() fd = open(‘fdw.txt‘,‘rb‘) print(pickle.load(fd)) fd.close()
output:
dumping dict to file... {‘name‘: <function func at 0x7fa1904d4488>}
{‘name‘: <function func at 0x7fa1904d4488>}
以上是关于python3.x 基础四:json与pickple的主要内容,如果未能解决你的问题,请参考以下文章