Reputation: 57
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
Upvotes: 0
Views: 2526
Reputation: 39778
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()
Upvotes: 1
Reputation: 57
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()
Upvotes: 0