Python - pickle模块

Pickle模块(example转自官方文档)

  1. 储存一个数据结构,用dump()方法
    pickle.dump(obj, file, protocol=None, *, fix_imports=True)
    obj: 要储存的数据结构
    file: 存入的文件

    import pickle
    
    # An arbitrary collection of objects supported by pickle.
    data = {
        'a': [1, 2.0, 3, 4+6j],
        'b': ("character string", b"byte string"),
        'c': {None, True, False}
    }
    
    with open('data.pickle', 'wb') as f:
        # Pickle the 'data' dictionary using the highest protocol available.
        pickle.dump(data, f, -1)	
    
  2. 加载数据结构,用load()方法
    pickle.load(file, *, fix_imports=True, encoding="ASCII", errors="strict")

    import pickle
    
    with open('data.pickle', 'rb') as f:
        # The protocol version used is detected automatically, so we do not
        # have to specify it.
        data = pickle.load(f)
    

猜你喜欢

转载自blog.csdn.net/weixin_39129504/article/details/82751008