ColdLuck
ColdLuck

Reputation: 25

Why does my code not work but also not have any errors?

so theres no error and no issue but just wont change the json file? heres the code:

@client.command()
@commands.check(is_owner)
async def points_give(member: discord.Member, amount:int=None):
    with open("users.json", "r") as f:
        users = json.load(f)
        await add_experience(users, member, amount)

async def add_experience(users, member, exp):
    with open('users.json', 'r')as f:
        users = json.load(f)
        users[member.id]["experience"] += exp```

Upvotes: 0

Views: 71

Answers (4)

Mixno
Mixno

Reputation: 412

Try this:

@client.command()
@commands.check(is_owner)
async def points_give(member: discord.Member, amount:int=0):
    with open("users.json", "r") as f:
        users = json.load(f)
    await add_experience(users, member, amount)

async def add_experience(users, member, exp):
    users[member.id]["experience"] += exp
    with open('users.json', 'w+') as f:
        json.dump(users, f)

Upvotes: 1

Reyhaneh Torab
Reyhaneh Torab

Reputation: 367

There may be some error in opening the file. its better to use try/except in your code. Then if there is an error, you can see that.

def Check(file):
    try:
      open(file, "w")
      return 1
    except IOError:
      print ("Error: File does not exist.")
      return 0
    Except:
      print ("Error")
      return 0

In your def:

result = Check("yourFileName")
if (result == 1):
      #Do what you want

To add to json data:

dict = {key_value_to_be_added}

with open('filename', 'r') as f:
    data = json.load(f)

data.update(dict)
with open('filename', 'w+') as f:
    json.dump(data, f)

Upvotes: 0

Boendal
Boendal

Reputation: 2526

I can see two issues.

First your async def add_experience(users, member, exp): already takes a parameter users. But you open the json file again and load the user anew.

Second you never write your added experience back into the file. So you update the experience point and forget about it as soon as you execute on of the two functions because you never write it back.

Maybe you had a typo in the 2nd function and didn't want to read the file anew and instead write the points back into the json?

Upvotes: 0

andole
andole

Reputation: 286

json.load() reads the file stream and returns a dictionary. If you want to change the value in the file then you need to open the file in write mode and use json.dump() to rewrite the file.

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

Upvotes: 0

Related Questions