updating a python dictionary saved in a python file

Viewed 457

Good Afternoon,

I have a python dictionary file I created using the following code :

playerdict = {('john','denver'):12345,('keneith','Noisewater'):23456}

The dictionary is very long so I saved it to a python file.

with open('playerdict.py','w') as file:
    file.write("playerdict = { \n")
    for k in sorted (playerdict.keys()):
        file.write("%s:%s, \n" % (k, playerdict[k]))
    file.write("}")

I can now import the dictionary using:

from playerdict import playerdict

What is the most pythonic way to update the dictionary with a new player? For instance I want to add k,v ('johhny B',good),34567. Is the only way to update the playerdict and then rewrite the entire file or is there a pythonic way to write the name to the file without rewriting the entire dictionary into a file each time a name is added.

Thank you so much in advance.

1 Answers

Change

with open('playerdict.py','w') as file:

to

with open('playerdict.py','a') as file:


Python File Modes
Mode    Description
'r'     Open a file for reading. (default)
'w'     Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists.
'x'     Open a file for exclusive creation. If the file already exists, the operation fails.
'a'     Open for appending at the end of the file without truncating it. Creates a new file if it does not exist.
't'     Open in text mode. (default)
'b'     Open in binary mode.
'+'     Open a file for updating (reading and writing)
Related