How can I use pickle to save a dict?

前端 未结 9 2405
说谎
说谎 2020-11-22 06:45

I have looked through the information that the Python docs give, but I\'m still a little confused. Could somebody post sample code that would write a new file then use pickl

9条回答
  •  半阙折子戏
    2020-11-22 07:35

    If you just want to store the dict in a single file, use pickle like that

    import pickle
    
    a = {'hello': 'world'}
    
    with open('filename.pickle', 'wb') as handle:
        pickle.dump(a, handle)
    
    with open('filename.pickle', 'rb') as handle:
        b = pickle.load(handle)
    

    If you want to save and restore multiple dictionaries in multiple files for caching and store more complex data, use anycache. It does all the other stuff you need around pickle

    from anycache import anycache
    
    @anycache(cachedir='path/to/files')
    def myfunc(hello):
        return {'hello', hello}
    

    Anycache stores the different myfunc results depending on the arguments to different files in cachedir and reloads them.

    See the documentation for any further details.

提交回复
热议问题