热线电话:13121318867

登录
2019-03-27 阅读量: 551
如何理解Python Pickling

Python pickle模块用于序列化和反序列化Python对象结构。可以对Python中的任何对象进行pickle,以便将其保存在磁盘上。pickle做的是它在将对象写入文件之前先“序列化”对象。Pickling是一种将python对象(list,dict等)转换为字符流的方法。这个想法是这个字符流包含在另一个python脚本中重建对象所需的所有信息。

# Python3 program to illustrate store

# efficiently using pickle module

# Module translates an in-memory Python object

# into a serialized byte stream—a string of

# bytes that can be written to any file-like object.

import pickle

def storeData():

# initializing data to be stored in db

Omkar = {'key' : 'Omkar', 'name' : 'Omkar Pathak',

'age' : 21, 'pay' : 40000}

Jagdish = {'key' : 'Jagdish', 'name' : 'Jagdish Pathak',

'age' : 50, 'pay' : 50000}

# database

db = {}

db['Omkar'] = Omkar

db['Jagdish'] = Jagdish

# Its important to use binary mode

dbfile = open('examplePickle', 'ab')

# source, destination

pickle.dump(db, dbfile)

dbfile.close()

def loadData():

# for reading also binary mode is important

dbfile = open('examplePickle', 'rb')

db = pickle.load(dbfile)

for keys in db:

print(keys, '=>', db[keys])

dbfile.close()

if __name__ == '__main__':

storeData()

loadData()

0.0000
0
关注作者
收藏
评论(0)

发表评论

暂无数据
推荐帖子