Store a dictionary in a file for later retrieval

前端 未结 5 2129
Happy的楠姐
Happy的楠姐 2021-01-02 05:43

I\'ve had a search around but can\'t find anything regarding this...

I\'m looking for a way to save a dictionary to file and then later be able to load it back into

5条回答
  •  时光说笑
    2021-01-02 05:49

    Python has the shelve module for this. It can store many objects in a file that can be opened up later and read in as objects, but it's operating system-dependent.

    import shelve
    
    dict1 = #dictionary
    dict2 = #dictionary
    
    #flags: 
    #   c = create new shelf; this can't overwrite an old one, so delete the old one first
    #   r = read
    #   w = write; you can append to an old shelf
    shelf = shelve.open("filename", flag="c")
    shelf['key1'] = dict1
    shelf['key2'] = dict2
    
    shelf.close()
    
    #reading:
    shelf = shelve.open("filename", flag='r')
    for key in shelf.keys():
        newdict = shelf[key]
        #do something with it
    
    shelf.close()
    

提交回复
热议问题