【问题标题】:Why does my code not work but also not have any errors?为什么我的代码不起作用但也没有任何错误?
【发布时间】:2020-04-08 02:57:06
【问题描述】:

所以没有错误也没有问题,只是不会更改 json 文件?代码如下:

@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```

【问题讨论】:

  • 我被告知将 ctx 作为第一个参数,但这也不起作用。没有错误

标签: python json discord discord.py


【解决方案1】:

json.load() 读取文件流并返回一个字典。 如果要更改文件中的值,则需要以写入模式打开文件并使用json.dump() 重写文件。

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

【讨论】:

    【解决方案2】:

    我可以看到两个问题。

    首先你的async def add_experience(users, member, exp): 已经有一个参数 users。但是您再次打开 json 文件并重新加载用户。

    其次,您永远不会将您添加的体验写回文件中。因此,您更新经验点并在执行这两个函数时立即忘记它,因为您永远不会将其写回。

    也许您在第二个函数中有错字,不想重新读取文件,而是将点写回 json?

    【讨论】:

      【解决方案3】:

      打开文件可能有一些错误。最好在代码中使用 try/except。然后如果有错误,你可以看到。

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

      在你的定义中:

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

      添加到 json 数据:

      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)
      

      【讨论】:

      • 如果不是太麻烦你可以直接编辑它,因为我很难理解
      • Mixno给出的答案正是我所说的。我只是解释在处理文件时调试代码的另一种方法。使用它是可选的。
      【解决方案4】:

      试试这个:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-23
        • 2021-09-23
        • 1970-01-01
        • 1970-01-01
        • 2021-09-22
        • 2021-12-25
        相关资源
        最近更新 更多