下午好,
我有一个使用以下代码创建的python字典文件:
playerdict = {('john','denver'):12345,('keneith','Noisewater'):23456}
字典很长,所以我将它保存到python文件中。
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("}")
我现在可以使用以下命令导入字典:
from playerdict import playerdict
用新播放器更新字典的最Python方式是什么?例如我要添加k,v('johhny B',good),34567。是更新playerdict然后重写整个文件的唯一方法,还是有一种pythonic的方法将名称写入文件,而无需每次添加名称时都将整个字典重新写入文件。
非常感谢。
更改
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)