So I have a YML file, and I'm trying to convert it to a different format. I found a YML format converter script and edited it to the best of my ability, and this is what I've come up with:

#!/bin/python
try:
    import yaml
except:
    print "Failed to import module: yaml"

f = open("config.yml")
fh = f.read()
f.close()

orig_dict = yaml.load(fh)

users = orig_dict['users']

space = "    "

print "users:"

for user in users:
    print space + user + ":"
    for category in users[user]:
        if category == "groups":
            print space * 2 + "group:"
            for category_groups in users[user][category]:
                print space * 2 + "- " + category_groups
        else:
            print space * 2 + "ERROR"

It works, but the one problem is that I don't want to include users in the group "default" in the converted file. I've tried several things such as if category_groups != "default": print space * 2 + "- " + category_groups but that only omits the group, not the entire user. Is there a way to either skip users in the default group while printing the file or remove them after the file is printed? Help is appreciated :)

Dani AI

Generated

A compact, reliable fix is to filter the loaded users mapping before any manual printing and then let PyYAML write the result. That avoids fragile print-format logic and makes it trivial to either exclude every user who belongs to the "default" group or keep only those members. As spotted, a key-name mismatch (e.g. "group" vs "groups") is a common cause of an empty result; confirm the exact keys in the loaded structure first.

import yaml

with open('config.yml') as fh:
    data = yaml.safe_load(fh)

users = data.get('users', {})

# exclude any user whose 'groups' list contains 'default'
filtered = {name: info for name, info in users.items()
            if 'groups' in info and 'default' not in info['groups']}

with open('out.yml', 'w') as out:
    yaml.safe_dump({'users': filtered}, out, default_flow_style=False)

If the intent is the opposite (keep only users in the "default" group), change the condition to if 'groups' in info and 'default' in info['groups']. For quick checks of the loaded structure, print a sample (keys and a single value) or use pprint to ensure the script is examining the data the way it’s expected to.

If a SyntaxError appeared earlier, common culprits are mixing tabs and spaces, stray non-ASCII characters from copy/paste, or an accidental typo. Running python -m py_compile script.py pinpoints the exact line. Prefer yaml.safe_load/safe_dump for safety and clarity rather than hand-assembling print output.

Recommended Answers

All 5 Replies

Add a function to filter users

def _my_users(users):
    for user in users:
        try:
            if not all(cg == "default" for cg in users[user]["group"]):
                yield user
        except KeyError:
            pass

my_users = list(_my_users(users))

for user in my_users:
    # ... etc

Where do I put this in the script? I tried putting it at the beginning and the end and I get SyntaxError: invalid syntax when I try to run it. Sorry, I have no experience with Python but all I could find that did something similar to what I needed was a Python script.

Where is the syntax error ? Are you using a very old version of python ?

I'm using 2.7.3 and I tried placing your code before and after the script I have, and I get the same error for both. Today I tried putting it in front of the script again like this:

def _my_users(users):
    for user in users:
        try:
            if not all(cg == "default" for cg in users[user]["group"]):
                yield user
        except KeyError:
            pass

my_users = list(_my_users(users))

for user in my_users:
    print space + user + ":"
    for category in users[user]:
        if category == "groups":
            print space * 2 + "group:"
            for category_groups in users[user][category]:
                print space * 2 + "- " + category_groups
        else:
            print space * 2 + "ERROR"

And it runs with no errors but the output file just says users: with nothing else under it... Is there any way to just say that if a user is in group "default", print their name and the group, and if not just skip it?

Sorry, I think I misspelled "group" instead of "groups". Can you try again ? What my code does is that it keeps all users for which there is a category_group in users[user]["groups"] which is different from "default".

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.