使用pickle
#import pickle
import cPickle as pickle
class Person:
def __init__(self,n,a):
self.name=n
self.age=a
def show(self):
print self.name+"_"+str(self.age)
aa = Person("JGood", 2)
aa.show()
f=open('p.txt','w')
pickle.dump(aa,f)
f.close()
#del Person
f=open('p.txt','r')
bb=pickle.load(f)
f.close()
bb.show()
使用json
# -*- coding: utf-8 -*-
import json
"""
使用json.dumps 将 json 格式的数据写到文件里
"""
measurements = [
{'weight': 392.3, 'color': 'purple', 'temperature': 33.4},
{'weight': 34.0, 'color': 'green', 'temperature': -3.1},
]
def store(measurements):
with open('measurements.json', 'w') as f:
f.write(json.dumps(measurements))
def load(filename='measurements.json'):
with open(filename, 'r') as f:
encode=f.read()
s=json.loads(encode)
print s
if __name__ == "__main__":
store(measurements)
load()