Austyn Howard
Austyn Howard

Reputation: 65

Updating Dict in File

I'm making a Python Discord bot for a server I'm a part of and one of the features the owners asked for is a command that will return the age of a user. I've managed to add it to file and then read that file and get good results. But whenever I attempt to add more users to the dictionary, it just adds a new dictionary into the file and messes everything up.

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)])

Upvotes: 2

Views: 57

Answers (1)

AKX
AKX

Reputation: 168893

You could use the built-in shelve module for a simple database you don't have to manage by hand.

It smells, API-wise, like a dictionary, but is actually backed by a file on the disk.

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.")

Upvotes: 1

Related Questions