1 import marshal #导入模块
2 x1=30 #待序列化的对象
3 x2=5.0
4 x3=[1,2,3]
5 x4=(4,5,6)
6 x5={'a':1,'b':2,'c':3}
7 x6={7,8,9}
8 x=[eval('x'+str(i)) for i in range(1,7)] #把需要序列化的对象放在一个列表中
9 print(x)
10 # [30, 5.0, [1, 2, 3], (4, 5, 6), {'c': 3, 'b': 2, 'a': 1}, {8, 9, 7}]
11 with open('test.dat','wb')as fp: #创建二进制文件
12 marshal.dump(len(x),fp) #先写入对象个数
13 for item in x:
14 marshal.dump(item,fp) #把2列表中的对象依次序列化并写入文件呢
15 with open('test.dat','rb')as fp:
16 n=marshal.load(fp) #获取对象个数
17 for i in range(n):
18 print(marshal.load(fp)) #反序列化,输出结果
19 # 30
20 # 5.0
21 # [1, 2, 3]
22 # (4, 5, 6)
23 # {'c': 3, 'b': 2, 'a': 1}
24 # {8, 9, 7}