这是问题的描述:
我的问题:我的目标是在python中为序列化的字典添加新值(序列化是使用Pickle模块完成的,并且字典将保存在文本文件中)首先从文件中添加新值,然后将序列化的字典重写到文件中。
我当前的代码:
def write(key,value): # parameters for the new dictionary variable
with open(file_loc,"r+") as file:
text=file.read() # load the content of the database
_dict= pickle.loads(text) # translate the serialized data to dictionary form
_dict[key]=value # the new variable added to the serialized dictionary
file.seek(0) # get to the first index-rewrite text
file.write(pickle.dumps(_dict) ) # write the new information to the file
我尝试过的操作:我知道可以使用Regex做到这一点,但我正在寻找一种可能更有效的方法。我查看了Pickle的文档以及与我类似的问题,但没有找到满足我需要的解决方案。