NEO
NEO

Reputation: 23

Adding values in a json file

I'm trying to add previously added integers in the json file. for discord.py

@client.command()
async def mine(ctx):
await open_account(ctx.author)

users = await get_wallet_data()

user = ctx.author


earnings = int(random.randrange(11))

em = discord.Embed(title = 'Mined NeoCoins')
em.add_field(name = 'Earnings:', value = earnings)
await ctx.send(embed = em)


wallet_amt = users[str(user.id)]['Wallet']
print(wallet_amt)
nw = wallet_amt =+ earnings
nw = users[str(user.id)]['Wallet']
print(nw)


with open('wallet.json','w') as f:
    users =  json.dump(users,f)

But I'm getting that same value. Not the added value

Upvotes: 2

Views: 42

Answers (1)

chrisgallardo
chrisgallardo

Reputation: 28

To change the values of .json files, you have to load the file first, make the edits, and then replace the file with the changed version.

Load file:

with open("filename.json", "w+") as fp:
    d = json.load(fp) #load the file as an object

Make edits:

    ... #change the values in d

Replace file with changed version:

    fp.truncate(0) #empty the file
    json.dump(d, fp) #dump changed version into file

Full Code

Upvotes: 1

Related Questions