Store a dictionary in a file for later retrieval

前端 未结 5 2135
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 06:05

    Two functions which create a text file for saving a dictionary and loading a dictionary (which was already saved before) for use again.

    import pickle
    
    def SaveDictionary(dictionary,File):
        with open(File, "wb") as myFile:
            pickle.dump(dictionary, myFile)
            myFile.close()
    
    def LoadDictionary(File):
        with open(File, "rb") as myFile:
            dict = pickle.load(myFile)
            myFile.close()
            return dict
    

    These functions can be called through :

    SaveDictionary(mylib.Members,"members.txt") # saved dict. in a file
    members = LoadDictionary("members.txt")     # opened dict. of members
    

提交回复
热议问题