如何使用 Python 更新文件中的字典?

How to update a dictionary in a file with Python?

我正在尝试从文件中获取字典,向其中添加一些数据并将其保存回同一个文件。当我 运行 程序时,它总是去除非它打印 1 并永远这样循环。我该如何解决?

这是我传递给函数的数据(这是示例数据 - 我实际上传递了一个密码和一个用随机密钥加密的用户名): 键:'␙⋉∡' 值:['␙⋉∡➵ᾁ\u1fd5ᾁ', 84, None]} file_name: 'database.database'

这是错误:

Traceback (most recent call last):
  File "C:\Users\HP\Currently_Working_On\Database_Login_Chat.py", line 46, in write_data
    file_data = eval(file_data)
  File "<string>", line 0
    
SyntaxError: unexpected EOF while parsing

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\HP\Currently_Working_On\Database_Login_Chat.py", line 52, in write_data
    file2.write(str(file_data))
  File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 2-3: character maps to <undefined>
def write_data(key, value, file_name):
    try:
        file = open(file_name, "r")
        file_data = str(file.read())
        file.close()

        file_data = eval(file_data)
        file_data[key] = value

        file_data = str(file_data)
        file2 = open(file_name, "w")
        print("1")
        file2.write(str(file_data))
        print("2")
        file2.close()
        print("3")
    except:
        file3 = open(file_name, "w")
        file3.write("{}")
        file3.close()
        print("0")
        write_data(key, value, file_name)

要通过编码错误,请尝试为代码的所有读写部分指定编码参数,如下所示:

...
file = open(file_name, "r", encoding='utf-8')
...
file2 = open(file_name, "w", encoding='utf-8')
...
file3 = open(file_name, "w", encoding='utf-8')
...