[简明Python教程3.2版本实现] pickling.py
初学Python3.2,发现与之前的Python2.x很多实现上存在差异。在此做下记录~
View Code
1 #!/usr/bin/python 2 # Filename : pickling.py 3 4 import pickle as p 5 # import pickle as p 6 7 shoplistfile = 'shoplist.data' 8 # the name of the file where we will shore the object 9 10 shoplist = ['apple', 'mango', 'carrot'] 11 12 # Write to the file 13 f = open(shoplistfile, 'wb') 14 p.dump(shoplist, f) # dump the object to a file 15 f.close() 16 17 del shoplist # remove the shoplist 18 19 # Read back from the shorage 20 f = open(shoplistfile, 'rb') 21 shoredlist = p.load(f) 22 print(shoredlist) 23 print('=======================') 24 25 a1 = 'apple' 26 b1 = {1: 'One', 2: 'Two', 3: 'Three'} 27 c1 = ['apple', 'mango', 'carrot'] 28 29 f1 = open('temp.pkl', 'wb') 30 p.dump(a1, f1) 31 p.dump(b1, f1) 32 p.dump(c1, f1) 33 34 f1.close() 35 36 f2 = open('temp.pkl', 'rb') 37 38 a2 = p.load(f2) 39 b2 = p.load(f2) 40 c2 = p.load(f2) 41 42 print(a2) 43 print(b2) 44 print(c2)
上段代码与简明教程里面的主要差异在于open函数中的'wb'及'rb',
按照教程上的'w'书写方式在python3.x版本里运行会出现异常。
后面教程没有的代码主要是在测试pickle的顺序储存及顺序取出特性。

浙公网安备 33010602011771号