更新保存在 python 文件中的 python 词典
updating a python dictionary saved in a python file
下午好,
我有一个 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
用新玩家更新字典最pythonic 的方法是什么?例如我想添加 k,v ('johhny B',good),34567。是更新 playerdict 然后重写整个文件的唯一方法,还是有一种 pythonic 方法将名称写入文件而无需在每次添加名称时将整个字典重写到文件中。
在此先感谢您。
改变
with open('playerdict.py','w') as file:
至
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)
下午好,
我有一个 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
用新玩家更新字典最pythonic 的方法是什么?例如我想添加 k,v ('johhny B',good),34567。是更新 playerdict 然后重写整个文件的唯一方法,还是有一种 pythonic 方法将名称写入文件而无需在每次添加名称时将整个字典重写到文件中。
在此先感谢您。
改变
with open('playerdict.py','w') as file:
至
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)