0

How can I add value to an existing list of YAML files using the discord.py command?

here's what I've tried:

@bot.command()
async def addwhitelist(ctx, id : int=None):
    with open("./config.yml", "r") as file:
      data = file.readlines()
    data[0][49] = f", {id}"

    with open("./config.yml", "w") as file:
      file.writelines(data)
      file.close()

and here's what's the list:

Whitelist: [483686172221243402, 740936250608844890]

NOTE: I want it to add more than once so whenever I want to add a new value to that list.

so how can I do that?

2 Answers2

1

You should probably use the pyyaml library:

import yaml
@bot.command()
async def addwhitelist(ctx, id):
    with open('./config.yml', 'r') as f:
        conf = yaml.safe_load(f)
        conf['Whitelist'].append(id)
    with open('./config.yml', 'w') as f:
        yaml.dump(conf, f)

The usage of discord.py here is irrelevant.

Jonno_FTW
  • 8,601
  • 7
  • 58
  • 90
0

So if I understand correctly, you have a YAML file where the first line looks like Whitelist: [483686172221243402, 740936250608844890].

You want to be able to add new numbers to this list. So for example adding a new number 83298234892891392 inside the list, while keeping the other numbers there.

To do this, I would do:

def whitelist(id: int):
    with open("./config.yml", "r") as file:
        lines = tuple(file)

    lines[0].removeprefix('Whitelist: ')
    whitelist = eval(lines[0])
    whitelist.append(id)
    lines[0] = 'Whitelist: ' + str(whitelist)

    with open("./config.yml", "w") as file:
        for line in lines:
            file.write(line)
ddg
  • 1,090
  • 1
  • 6
  • 17