'''
Pickle模块中最常用的函数为:
(1)pickle.dump(obj, file, [,protocol])
函数的功能:将obj对象序列化存入已经打开的file中。
参数讲解:
obj:想要序列化的obj对象。
file:文件名称。
protocol:序列化使用的协议。如果该项省略,则默认为0。如果为负值或HIGHEST_PROTOCOL,则使用最高的协议版本。
(2)pickle.load(file)
函数的功能:将file中的对象序列化读出。
参数讲解:
file:文件名称。
(3)pickle.dumps(obj[, protocol])
函数的功能:将obj对象序列化为string形式,而不是存入文件中。
参数讲解:
obj:想要序列化的obj对象。
protocal:如果该项省略,则默认为0。如果为负值或HIGHEST_PROTOCOL,则使用最高的协议版本。
(4)pickle.loads(string)
函数的功能:从string中读出序列化前的obj对象。
参数讲解:
string:文件名称。
【注】 dump() 与 load() 相比 dumps() 和 loads() 还有另一种能力:dump()函数能一个接着一个地将几个对象序列化存储到同一个文件中,随后调用load()来以同样的顺序反序列化读出这些对象。
'''
# pickle模块主要函数的应用举例
import pickle
dataDic = {}
data1 = {}
help = u'''
1:add a word
2:find a word meaning
3: delete a word
input bye to exit
'''
print help
while True:
command = raw_input("please input your command:\n")
if command == str(1):
word = raw_input("please input your word:")
word_meaning = raw_input("please input your word meaning:")
fr = open('dataFile.kpl', 'rb')
data1 = pickle.load(fr)
if data1.has_key(word):
print '你输入的单词已经存在了!!'
fr.close()
continue
fw = open('dataFile.kpl', 'wb')
dataDic[word] = word_meaning
pickle.dump(dataDic, fw)
print '单词添加完毕!'
fw.close()
if command == str(2):
word = raw_input("please input your word to find:")
fr = open('dataFile.kpl', 'rb')
data1 = pickle.load(fr)
if data1.has_key(word):
print '你查找的单词是:',data1[word]
fr.close()
continue
print '你找的单词不存在!'
if command == str(3):
word = raw_input("please input your word to delete:")
fr = open('dataFile.kpl', 'rb')
data1 = pickle.load(fr)
if data1.has_key(word):
print '你要删除单词是:', data1[word]
del data1[word]
print '删除成功!,欢迎下次再使用!!'
fr.close()
continue
print "word to delete is not found!"
if command == "bye":
print '欢迎下次在次使用!!'
break
1:add a word
2:find a word meaning
3: delete a word
input bye to exit
please input your command:
1
please input your word:lwen
please input your word meaning:kk
单词添加完毕!
please input your command:
1
please input your word:liwen
please input your word meaning:美丽的开始
单词添加完毕!
please input your command:
1
please input your word:liwen
please input your word meaning:美丽的开始
你输入的单词已经存在了!!
please input your command:
乘法
please input your command:
1
please input your word:加油
please input your word meaning:加油
单词添加完毕!
please input your command:
2
please input your word to find:加油
你查找的单词是: 加油
please input your command:
3
please input your word to delete:加油
你要删除单词是: 加油
删除成功!,欢迎下次再使用!!
please input your command:
欢迎下次在次使用!
bye
=============================
dataList=[1,3,4,5,[34,4,5]]
dataDic = {'a':1,'b':3}
下面是参考代码:
# 使用dump()将数据序列化到文件中
fw = open('dataFile.kpl', 'wb')
# Pickle the list using the highest protocol available.
pickle.dump(dataList, fw, -1)
# Pickle dictionary using protocol 0.
pickle.dump(dataDic, fw)
fw.close()
# 使用load()将数据从文件中序列化读出
fr = open('dataFile.kpl', 'rb')
data1 = pickle.load(fr)
print(data1)
data2 = pickle.load(fr)
print(data2)
fr.close()
# 使用dumps()和loads()举例
p = pickle.dumps(dataList)
print(pickle.loads(p))
p = pickle.dumps(dataDic)
print(pickle.loads(p))