在不加载值的情况下将其添加到序列化字典中

这是问题的描述:

我的问题:我的目标是在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的文档以及与我类似的问题,但没有找到满足我需要的解决方案。

aaawenaaa 回答:在不加载值的情况下将其添加到序列化字典中

def write(key,value):
  num_lines = sum(1 for line in open('content.txt'))
  serializaed_value = my_custom_serializer(value)
  with open("content.txt","a") as content_file:
    content_file.write("appended text")
    content_file.write("\n")
  with open("key.txt","a") as key_file:
    key_file.write("{}:{}\n".format(key,num_lines))

def read(key):
  with open("key.txt","r") as key_file:
    line_num = None
    while line_num == None:
      for line in key_file:
        if key in line:
          line_num = line.split(":")[1]
      if line_num == None:
        raise Exception()
    with open("content.txt","a") as content_file:
      for i,line in enumerate(content_file):
        if i == line_num:
           return my_custom_deserializer(line)
      raise Exception("Line number not found")

然后,您只需要实现串行器和解串器。而且,由于这是您的目标,因此可以在该部分中使用泡菜。

编辑:该代码未经测试,几乎没有错误处理。它还意味着一次只能和一个针对内容和密钥文件运行的应用程序一起使用。

此外,如果您选择将pickler用于序列化和反序列化部分,则base64将在pickle dump之后对值进行编码,并在pickle加载之前进行解码。这将有助于避免content.txt文件中不需要的字符出现问题。

本文链接:https://www.f2er.com/3107693.html

大家都在问