python对象与文件之间的序列化和反序列化:
pickle.dump()
pickle.load()
pickle.dump(obj, file, [,protocol])
protocol=>0 ASCII,1 older protocol,2 new protocol, it is necessary to open with'rb,wb'if protocal>=1
pickle.load(file)
1 import pickle 2 3 #can pickleable something like tuple,set list dictionary 4 table = { 5 'jack': 90, 6 'bob': 80, 7 'c': 85 8 } 9 10 with open('table.plk', 'wb') as f: 11 #pickle.dump(obj, file, [,protocol]) 12 #protocol 0:ASCII(default) 1:older protocol,2 newer protocol 13 #open with "wb" since the protocol is set highest as -1 14 pickle.dump(table, f,-1) 15 16 17 with open('table.plk', 'rb') as f: 18 # pickle.load(file) 19 table = pickle.load(f) 20 print table
python对象和字符串间的序列化和反序列化
obj2=pickle.dumps(obj)
obj1=pickle.loads(obj2)
1 >>> table = {'tom': 85, 'bob': 80, 'jack': 90} 2 >>> import pickle 3 >>> table = {'tom': 85, 'bob': 80, 'jack': 90} 4 >>> p=pickle.dumps(table) 5 >>> print p 6 (dp0 7 S'bob' 8 p1 9 I80 10 sS'jack' 11 p2 12 I90 13 sS'tom' 14 p3 15 I85 16 s. 17 >>> type(p) 18 <type 'str'> 19 >>> t2=pickle.loads(p) 20 >>> print t2 21 {'bob': 80, 'jack': 90, 'tom': 85} 22 >>> type(t2) 23 <type 'dict'>