首页 > 代码库 > pickle使用

pickle使用

1.存、取单个对象

>>> import pickle
>>> student_info = {name:peter,age:20}
>>> f = open(student.pkl,w)
>>> pickle.dump(student_info,f) #数据保存到文件
>>> f.close()
>>> s = pickle.load(f)  #从文件中读取数据,生成相应的对象
>>> s
{age: 20, name: peter}
>>> f.tell()  #加载文件后,文件的读写指针发生了偏移,这是从文件中加载多个对象的基础
45
>>> f.close()


[hupeng@hupeng-vm class]$cat student.pkl 
(dp0
Sage
p1
I20
sSname
p2
Speter
p3

2.存、取多个对象

>>> student_list = [{name:student_%d %(i)}for i in range(5)]
>>> student_list
[{name: student_0}, {name: student_1}, {name: student_2}, {name: student_3}, {name: student_4}]
>>> f = open(students.pkl,w)
>>> for i in range(5):
...     pickle.dump(student_list[i],f)  #逐条写入
... 
>>> f.close()
>>> f = open(students.pkl,r)
>>> while True:
...     try:
...         print pickle.load(f)
...         print file offset:, f.tell()  #读取一次文件,文件指针发生向后偏移
...     except EOFError: #读到文件结尾
...         break
... 
{name: student_0}
file offset: 34
{name: student_1}
file offset: 68
{name: student_2}
file offset: 102
{name: student_3}
file offset: 136
{name: student_4}
file offset: 170

[hupeng@hupeng-vm class]$cat students.pkl 
(dp0
Sname
p1
Sstudent_0
p2
s.(dp0
Sname
p1
Sstudent_1
p2
s.(dp0
Sname
p1
Sstudent_2
p2
s.(dp0
Sname
p1
Sstudent_3
p2
s.(dp0
Sname
p1
Sstudent_4
p2

3.自定义对象

custom_class.py

# coding=utf-8


class MyClass(object):
    def __init__(self):
        self.data = []

    def __str__(self):
        return Custom Class MyClass Data:%s %(self.data)
    
    def add_item(self, item):
        self.data.append(item)

写:

custom_class_pickle.py

# coding=utf-8
import pickle
import custom_class


obj = custom_class.MyClass()
obj.add_item(1)
obj.add_item(2)
obj.add_item(3)
obj.add_item(4)

f = open(custom_class.pkl,w)
pickle.dump(obj, f)
f.close()

读:

custom_class_unpickle.py

# coding=utf-8
import pickle
#import custom_class

f = open(custom_class.pkl,r)
obj = pickle.load(f)
f.close()
print obj 

注意:

对于unpickle代码,无须明确地加载正在unpickle的自定义类。但是,为了unpickle代码能够自定义类所在的模块

则是必须的。否则可能会出现如下错误:

技术分享

 

pickle使用