首页 > 编程语言 > 详细

python3.x 基础四:json与pickple

时间:2017-11-27 15:48:01      阅读:232      评论:0      收藏:0      [点我收藏+]
  • 每次打开一个文件,只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

原文:http://www.cnblogs.com/jenvid/p/7904253.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!