Python 更新文件中的Dict

Python 更新文件中的Dict,python,python-3.x,discord.py,Python,Python 3.x,Discord.py,我正在为我所属的服务器制作一个Python Discord bot,其所有者要求的功能之一是返回用户年龄的命令。我成功地将它添加到文件中,然后读取该文件并获得良好的结果。但每当我试图向字典中添加更多用户时,它只会向文件中添加一个新字典,并将一切都搞糟 users_age = {} @bot.command(pass_context=True) async def addAge(ctx, member : discord.Member, age : int): users_age[str

我正在为我所属的服务器制作一个Python Discord bot,其所有者要求的功能之一是返回用户年龄的命令。我成功地将它添加到文件中,然后读取该文件并获得良好的结果。但每当我试图向字典中添加更多用户时,它只会向文件中添加一个新字典,并将一切都搞糟

users_age = {}

@bot.command(pass_context=True)
async def addAge(ctx, member : discord.Member, age : int):
    users_age[str(member.mention)] = age
    fh = open('age.txt', 'a')
    fh.write(str(users_age))
    await bot.say("File written successfully!")
    fh.close()

@bot.command(pass_context=True)
async def Age(ctx, member : discord.Member):
    users_age = eval(open('age.txt', 'r').read())
    await bot.say(users_age[str(member.mention)])
您可以将用于不必手动管理的简单数据库

就API而言,它闻起来像一本字典,但实际上是由磁盘上的一个文件支持的

import shelve


@bot.command(pass_context=True)
async def addAge(ctx, member: discord.Member, age: int):
    with shelve.open("ages") as age_db:
        age_db[str(member.mention)] = age
    await bot.say("File written successfully!")


@bot.command(pass_context=True)
async def Age(ctx, member: discord.Member):
    with shelve.open("ages") as age_db:
        age = age_db.get(str(member.mention))
    if age is not None:
        await bot.say(age)
    else:
        await bot.say("I don't know.")

唉,不要使用
eval
,这是邪恶的。使用
eval()
是我让它正常工作的唯一方法。否则我会得到
TypeError
。问题是你正在使用
fh.write(str(users_age))
并假装它是序列化。事实并非如此。使用内置的基于文本的序列化格式,如带有
JSON
模块的JSON。在下面的回答中,您可以看到一种从discord bot将字典持久化到JSON文件的方法: