python数据保存

来源:互联网 发布:网页数据采集器 开源 编辑:程序博客网 时间:2024/06/07 13:01

使用pickle


#import pickleimport 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 sif __name__ == "__main__":    store(measurements)    load()


0 0
原创粉丝点击