使用cPickle进行数据的读取与保存
导入 cPickle:
import cPickle
dump()函数接受一个文件句柄和一个数据对象(列表 元组 字典 类对象等)作为参数,把数据对象保存到文件中。
使用load()函数从文件中读取数据时,pickle可以恢复数据本来的格式。
例:
list/dict等的保存与读取
list:
保存:
lis = [1,132, 98,'ABS']
cPickle.dump(lis, open("list.pkl","w"))
读取:
cPickle.load(open("list.pkl","r"))
或
保存:
cPickle.dump(lis, open("s.txt", "wb"))
读取:
cPickle.load(open("s.txt", "rb"))
字典:
保存:
dic = {'A':65, 'B':66, 'C':67}
cPickle.dump(dic, open("dictionary.pkl","w"))
读取:
cPickle.load(open("dictionary.pkl","r"))
字符串:
保存:
s = "This is a string !"
cPickle.dump(s, open("string.pkl","w"))
读取:
cPickle.load(open("string.pkl","r"))
类对象:
# 构造一个简单的Student类
class Student(object):
def __init__(self, name, age):
self.name = name
self.age = age
# 构造类对象
student = Student("Marry", 20)
# 保存类对象
cPickle.dump(student, open("studentdata.pkl", "w"))
# 读取类对象
st = cPickle.load(open("studentdata.pkl","r"))
print st.name, st.age
输出:
Marry 20