Python——pickle

Python pickle


关于pickle模块

  • Python的一个序列化与反序列化模块,支持Python基本数据类型
  • 可以处理自定义的类对象,方法等

内存中使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import pickle

origin = [1, 2, 3, [4, 5, 6]]
print "origin: %s" % origin
temp = pickle.dumps(origin)
print "temp: %s" % temp
new = pickle.loads(temp)
print "new: %s" % new

# output:
origin: [1, 2, 3, [4, 5, 6]]
temp: (lp0
I1
aI2
aI3
a(lp1
I4
aI5
aI6
aa.
new: [1, 2, 3, [4, 5, 6]]

硬盘中使用

1
2
3
4
5
6
7
8
9
10
11
12
13
import pickle

origin = [1, 2, 3, [4, 5, 6]]
print "origin: %s" % origin
# open a binary and write the result
pickle.dump(origin, open('temp', 'wb'))
# open a binary and read the original object
new = pickle.load(open('temp', 'rb'))
print "new: %s" % new

# output
origin: [1, 2, 3, [4, 5, 6]]
new: [1, 2, 3, [4, 5, 6]]