pickle文件序列化

1.使用pickle将list序列化

# -*- coding: cp936 -*-
'''
pickle一个list,将数据写入文件
'''
import pickle
d = range(0,200,5)
f = file("c:\\pickleList.dat","w")
p = pickle.dump(d,f)
f.close()
2.将序列化的数据读入
# -*- coding: cp936 -*-
'''
pickle一个list,将数据从文件中读取出来
'''
import pickle
f = file("c:\\pickleList.dat","r")
p = pickle.load(f)
f.close()
print p
与list相同的还有:
  • None, True, and False
    • integers, long integers, floating point numbers, complex numbers
    • normal and Unicode strings
    • tuples, lists, sets, and dictionaries containing only picklable objects
      3.将函数序列化
      # -*- coding: cp936 -*-
      '''使用pickle序列化对象
      1.将pickleTest写入文件
      2.函数、类pickle的是refence不是value
      '''
      import pickle
      def pickleTest(val = None):
          print val
      l = [pickleTest,pickleTest]
      f = file("c:\\pickleTest.dat","wb")
      p = pickle.dump(pickleTest,f)
      f.close()
      4.将函数从文件中读取出来
      # -*- coding: cp936 -*-
      '''使用pickle序列化对象
      1.使用load从文件中载入对象,并执行代码
      2.必须使用import,pickle不会对函数的代码进行处理
      '''
      import pickle
      import test
      f = file("c:\\pickleTest.dat","rb")
      p = pickle.load(f)
      f.close()
      p("jcodeer")
      与函数相同的还有如下:
    • functions defined at the top level of a module
    • built-in functions defined at the top level of a module
    • classes that are defined at the top level of a module
    • instances of such classes whose __dict__ or __setstate__() is picklable