JSON写不会被拒绝

时间:2018-12-17 17:45:39

标签: python discord.py

运行updatePrice命令时,如果某项不在json文件的列表中,则应该拒绝该项,而只是将其添加到列表的底部并接受。

@client.command(name='updatePrice',aliases= ['up'], pass_context=True)
async def update_price(ctx, item: str, quantity: float):
if (ctx.message.author.id in adminUsers):
    item = item.replace(" ", "").lower()
    with open(CONFIG, 'r+') as f:
        data = json.load(f)
        try:
            items[item] = quantity
            data['items'] = items
            f.seek(0)
            json.dump(data, f, indent=4)
            f.truncate()
            await client.say('{item} price updated'.format(item = item))
        except KeyError:
            await client.say('No match found for ' + item)
else:
    await client.say('You are not permitted to update item prices')

2 个答案:

答案 0 :(得分:0)

让我猜:您来自C#或Java背景,并且假设items[item] = ...抛出KeyError(如果该键尚不存在)。

但是,请查看Dictionaries exampleitems[item] = ...将添加或更改项目。

如果要检查某个项目是否在列表中,请使用... in items

示例代码:

from pprint import *
items = { "test":"something"}
items["new"] = "else"
pprint(items)
print ("not" in items)

答案 1 :(得分:0)

我重写了命令

async def update_price(ctx, item: str, quantity: float):
    item = item.replace(" ", "").lower()
    with open(CONFIG, 'r+') as f:
        data = json.load(f)
        if item in items:
            items[item] = quantity
            data['items'] = items
            f.seek(0)
            json.dump(data, f, indent=4)
            f.truncate()
            await ctx.send(f'{item} price updated')
        else:
            await ctx.send('No match found for ' + item)
        return