Saving an Object (Data persistence)

前端 未结 4 1076
你的背包
你的背包 2020-11-21 23:54

I\'ve created an object like this:

company1.name = \'banana\' 
company1.value = 40

I would like to save this object. How can I do that?

4条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 00:03

    Quick example using company1 from your question, with python3.

    import pickle
    
    # Save the file
    pickle.dump(company1, file = open("company1.pickle", "wb"))
    
    # Reload the file
    company1_reloaded = pickle.load(open("company1.pickle", "rb"))
    

    However, as this answer noted, pickle often fails. So you should really use dill.

    import dill
    
    # Save the file
    dill.dump(company1, file = open("company1.pickle", "wb"))
    
    # Reload the file
    company1_reloaded = dill.load(open("company1.pickle", "rb"))
    

提交回复
热议问题