简体   繁体   中英

How can I remove a value from a specific key in YAML with Python?

I have successfully worked out the addition of a value to a key in YAML with Python, and started to work on the reverse of it with reference to the code for addition. Here is my proposal of how the code work:

connected_guilds:
- 1
- 2

after the code is ran, the YAML file should be changed to:

connected_guilds:
- 1

Here is my code, however it didn't work, it ended up completely wiping out and the remaining is the -1 in the first YAML example I enclosed.

with open('guilds.yaml', 'r+') as guild_remove:
    loader = yaml.safe_load(guild_remove)

    content = loader['connected_guilds']

    for server in content:
        if server != guild_id:
            continue
        else:
            content.remove(guild_id)

            guild_remove.seek(0)

            yaml.dump(content, guild_remove)

            guild_remove.truncate()

I'd be grateful if anyone could help me out:D

Don't try to reimplement searching for the item to remove when Python already provides this to you:

with open('guilds.yaml', 'r+') as guild_remove:
    content = yaml.safe_load(guild_remove)
    content["connected_guilds"].remove(guild_id)
    guild_remove.seek(0)
    yaml.dump(content, guild_remove)
    guild_remove.truncate()

Here is the solution(with reference to the addition code):

with open('guilds.yaml', 'r+') as guild_remove:
    loader = yaml.safe_load(guild_remove)

    content = loader['connected_guilds']

    for server in content:
        if server != guild_id:
            continue
        else:
            content.remove(guild_id)

            guild_remove.seek(0)

            yaml.dump({'connected_guilds': content}, guild_remove)

            guild_remove.truncate()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM