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
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>}
原文:http://www.cnblogs.com/jenvid/p/7904253.html