zoukankan      html  css  js  c++  java
  • python文件操作:pickle模块多次dump后出现的读取问题

    pickle模块在python中是用于数据持久化的,基本用法涉及到的也就是dump和load,亦或者dumps和loads。

    pickle在使用过程中有一个特点,就是由于其特殊的内容标记,使得文件dump几次,就必须load几次才能将数据全部读出来,用代码来展现就是如下形式:

    import pickle
    
    a=1
    b=2
    c=3
    with open("ceshi.txt","wb") as f:
        pickle.dump(a,f)
        pickle.dump(b,f)
        pickle.dump(c,f)
    
    f=open("ceshi.txt","rb")
    with open("ceshi.txt","rb") as f :
        print(pickle.load(f))

    最终结果为:

    1

    如果想要读取全部的值,那么只能是dump了几次,就load几次,如下:

    import pickle
    
    a=1
    b=2
    c=3
    with open("ceshi.txt","wb") as f:
        pickle.dump(a,f)
        pickle.dump(b,f)
        pickle.dump(c,f)
    
    f=open("ceshi.txt","rb")
    with open("ceshi.txt","rb") as f :
        print(pickle.load(f))
        print(pickle.load(f))
        print(pickle.load(f))

    最终结果为:

    1

    2

    3

    我们在后续读写文件时,不可能记住所有的dump次数,也就无法准确的使用load多次的方式来取出值。我们可以使用另外一种方式来进行曲线救国:

    直接无限循环执行pickle.load命令,直至其报错才停止。

    import pickle
    
    a=1
    b=2
    c=3
    with open("ceshi.txt","wb") as f:
        pickle.dump(a,f)
        pickle.dump(b,f)
        pickle.dump(c,f)
    
    f=open("ceshi.txt","rb")
    with open("ceshi.txt","rb") as f :
       while True:
            try:
                print(pickle.load(f))
            except:
                break

    最终结果为:

    1

    2

    3

    通过这种方式,我们也可以做到将pickle生成的文件内容全部取出来。

  • 相关阅读:
    The executable was signed with invalid entitlements
    iOS7 文本转语音 AVSpeechSynthesizer
    The document "ViewController.xib" could not be opened. Could not read archive.
    UIPanGestureRecognizer
    UINavigationController
    IE6下面的css调试工具
    15款最好的网站音乐播放器
    ASP.NET常用加密解密方法
    ASP.NET根据IP获取省市地址
    强悍的CSS工具组合:Blueprint, Sass, Compass
  • 原文地址:https://www.cnblogs.com/mstzkot/p/7261542.html
Copyright © 2011-2022 走看看