• Python中使用pickle持久化对象


    Python中可以使用 pickle 模块将对象转化为文件保存在磁盘上,在需要的时候再读取并还原。具体用法如下:

    1
    pickle.dump(obj, file[, protocol])

    这是将对象持久化的方法,参数的含义分别为:
    obj: 要持久化保存的对象;
    file: 一个拥有 write() 方法的对象,并且这个 write() 方法能接收一个字符串作为参数。这个对象可以是一个以写模式打开的文件对象或者一个 StringIO 对象,或者其他自定义的满足条件的对象。
    protocol: 这是一个可选的参数,默认为 0 ,如果设置为 1 或 True,则以高压缩的二进制格式保存持久化后的对象,否则以ASCII格式保存。

    对象被持久化后怎么还原呢?pickle 模块也提供了相应的方法,如下:

    1
    pickle.load(file)

    只有一个参数 file ,对应于上面 dump 方法中的 file 参数。这个 file 必须是一个拥有一个能接收一个整数为参数的 read() 方法以及一个不接收任何参数的 readline() 方法,并且这两个方法的返回值都应该是字符串。这可以是一个打开为读的文件对象、StringIO 对象或其他任何满足条件的对象。

    下面是一个基本的用例:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    # -*- coding: utf-8 -*-
     
    import pickle
    # 也可以这样:
    # import cPickle as pickle
     
    obj = {"a": 1, "b": 2, "c": 3}
     
    # 将 obj 持久化保存到文件 tmp.txt 中
    pickle.dump(obj, open("tmp.txt", "w"))
     
    # do something else ...
     
    # 从 tmp.txt 中读取并恢复 obj 对象
    obj2 = pickle.load(open("tmp.txt", "r"))
     
    print obj2

    不过实际应用中,我们可能还会有一些改进,比如用 cPickle 来代替 pickle ,前者是后者的一个 C 语言实现版本,拥有更快的速度,另外,有时在 dump 时也会将第三个参数设为 True 以提高压缩比。再来看下面的例子:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    # -*- coding: utf-8 -*-
     
    import cPickle as pickle
    import random
    import os
     
    import time
     
    LENGTH = 1024 * 10240
     
    def main():
        d = {}
        a = []
        for i in range(LENGTH):
            a.append(random.randint(0, 255))
         
        d["a"] = a
         
        print "dumping..."
         
        t1 = time.time()
        pickle.dump(d, open("tmp1.dat", "wb"), True)
        print "dump1: %.3fs" % (time.time() - t1)
         
        t1 = time.time()
        pickle.dump(d, open("tmp2.dat", "w"))
        print "dump2: %.3fs" % (time.time() - t1)
         
        s1 = os.stat("tmp1.dat").st_size
        s2 = os.stat("tmp2.dat").st_size
         
        print "%d, %d, %.2f%%" % (s1, s2, 100.0 * s1 / s2)
         
        print "loading..."
         
        t1 = time.time()
        obj1 = pickle.load(open("tmp1.dat", "rb"))
        print "load1: %.3fs" % (time.time() - t1)
         
        t1 = time.time()
        obj2 = pickle.load(open("tmp2.dat", "r"))
        print "load2: %.3fs" % (time.time() - t1)
     
     
    if __name__ == "__main__":
        main()

    在我的电脑上执行结果为:

    dumping…
    dump1: 1.297s
    dump2: 4.750s
    20992503, 68894198, 30.47%
    loading…
    load1: 2.797s
    load2: 10.125s

    可以看到,dump 时如果指定了 protocol 为 True,压缩过后的文件的大小只有原来的文件的 30% ,同时无论在 dump 时还是 load 时所耗费的时间都比原来少。因此,一般来说,可以建议把这个值设为 True 。

    另外,pickle 模块还提供 dumps 和 loads 两个方法,用法与上面的 dump 和 load 方法类似,只是不需要输入 file 参数,输入及输出都是字符串对象,有些场景中使用这两个方法可能更为方便。

  • 相关阅读:
    Qt代码覆盖率code coverage(VS版)
    Qt下Doxygen使用
    QMultiMap使用
    Qt在VS(Visual Studio)中使用
    Qt语言家(Qt Linguist)更新翻译报错Qt5.9MinGW
    Qt Creator插件Todo
    QWidget一生,从创建到销毁事件流
    Qt排序
    QTcpSocketQt使用Tcp通讯实现服务端和客户端
    Qt Creator子目录项目类似VS解决方案
  • 原文地址:https://www.cnblogs.com/andy-0212/p/10626424.html
Copyright © 2020-2023  润新知