pickle模块以特殊的二进制格式保存和恢复数据对象

  • 先用pickle模块进行数据对象的存储
     1 import pickle
     2 
     3 data1 = {'a': [1, 2, 3, 9],
     4          'b': ('string', 'Unicode string'),
     5          'c': ('True','False')
     6          }
     7 
     8 list1 = [1, 2, 3]
     9 
    10 output = open('pkl_file', 'wb')
    11 
    12 pickle.dump(data1, output)
    13 
    14 pickle.dump(list1, output)
    15 
    16 output.close()

    如果你对open()函数还不够了解的话,建议看官方文档(不需要刻意去记,用到随时查):http://www.runoob.com/python/python-func-open.html 就知道'wb'、'rb'的意思了。pickle.dump(对象,文件,序列化使用的版本)

  1. 0:ASCII协议,所序列化的对象使用可打印的ASCII码表示

  2. 1:老式的二进制协议

  3. 2:2.3版本引入的新二进制协议,较以前的更高效。其中协议0和1兼容老版本的python。protocol默认值为0。

上边代码的意思是将data1和list1对象以二进制的形式写入文件pkl_file中(此时你可以在自己的项目下边看到这个文件名)但是怎么把文件的内容读取出来呢???Following me

  • 接着用pickle模块进行数据对象的解析(此时再创建一个新的python file)
    import  pickle
    
    pkl_file = open('pkl_file', 'rb')
    
    data1 = pickle.load(pkl_file)
    
    print(data1)
    
    list1 = pickle.load(pkl_file)
    print(list1)
    
    pkl_file.close()
    

    这时候data1和list1的内容就被读取出来了。

坚守自己的梦想比什么都重要!

 

 

补10个六级单词:

  1. abbreviation (n)缩写词;缩写
  2. abide(v)容忍,忍受
  3. abreast(ad)并排,并肩
  4. acclaim(vt)称赞;(n)赞赏
  5. acupuncture(n)针刺
  6. advent(n)出现,到来
  7. adversary(n)对手;(a)对手的
  8. afloat(ad\a)漂浮的(地),在船上的(地)
  9. agitate(v)鼓动,煽动;使焦虑不安
  10. ail(v)困扰;使难受

猜你喜欢

转载自www.cnblogs.com/ttdeveloping/p/9814433.html
今日推荐