我如何从json文件中删除某些内容

时间:2019-10-04 00:09:22

标签: python json python-3.x discord.py-rewrite

我不确定如何从.json文件中删除内容

我尝试查找它,但还是没什么:(

dat <- read.table(text = " Estuary                     Site Year   avg_rate        ER
1  'Fortrose Estuary'  'Northern Flats Sediment'  2018         NA       NaN
2  'Fortrose Estuary'  'Northern Flats Sediment'  2019 -0.6666667 3.7107951
3  'Fortrose Estuary'          'Site A Sediment'  2019         NA       NaN
4  'Fortrose Estuary'          'Site B Sediment'  2009         NA       NaN
5  'Fortrose Estuary'          'Site B Sediment'  2011 -2.7500000 3.5707142
6  'Fortrose Estuary'          'Site B Sediment'  2012 -1.5000000 6.7577116
7  'Fortrose Estuary'          'Site B Sediment'  2013  1.5000000 3.8729833
8  'Fortrose Estuary'          'Site B Sediment'  2015 -0.6625000 3.7063853
9  'Fortrose Estuary'          'Site B Sediment'  2016  4.0750000 2.6612967
10 'Fortrose Estuary'          'Site B Sediment'  2018 -4.5000000 0.8164966
11 'Fortrose Estuary'          'Site B Sediment'  2019  6.9000000 4.2237424",
                  header = TRUE, stringsAsFactors = FALSE)

没有错误

1 个答案:

答案 0 :(得分:0)

我不确定您希望命令执行什么操作,但这是一个示例,说明如何将json实现为discord.py。

在这里,无论何时执行命令,机器人都会打开一个json文件,读取数据,然后查看消息作者是否在数据中。如果作者在数据中,则将键/值对删除,并将数据重写到json文件中:

import json

@bot.command()
async def afkremoveme(ctx):

    f = "yourFile.json"
    author = str(ctx.author.id)

    with open(f, "r") as read_file:
        data = json.load(read_file)

    if author in data: # if any key in the dictionary is an integer, it is converted to a string when a json file is written

        del data[author]
        newData = json.dumps(data, indent=4)

        with open(f, "w") as write_file:
            write_file.write(newData)

        await ctx.send(f"{ctx.author.display_name} is no longer afk...")

这正在读取一个看起来像这样的json文件(用您的ID替换000000):

{
    "000000" : "afk",
    "someOtherGuy" : "afk"
}

所有这些都使用字典和json模块。如果您不熟悉这两个概念,这里有一些链接可以帮助您:-)

Python DictionariesPython-Json