Search code examples
pythonpython-2.7yamlpyyaml

Convert text file to yaml in python


I have a text file in the below format:

{'Server Type: ABCDDEER' :['name: abcd01t' ,'IP: 127.12.32.52', 'tags: ALL, APP,EER, REER1']},
{'Server Type: ABCDDEER' :['name: abcd02t' ,'IP: 127.12.32.53', 'tags: ALL, APP,EER, REER2']},
{'Server Type: ABCDDEER' :['name: abcd03t' ,'IP: 127.12.32.54', 'tags: ALL, APP,EER, REER1']},
{'Server Type: ABCDDEER' :['name: abcd04t' ,'IP: 127.12.32.55', 'tags: ALL, APP,EER, REER2']},
{'Server Type: ABCDDPP' :['name: abcd1t' ,'IP: 127.12.32.36', 'tags: ALL, APP,PP,  PP1']},
{'Server Type: ABCDDPP' :['name: abcd2t' ,'IP: 127.12.32.37', 'tags: ALL, APP,PP,  PP2']},
{'Server Type: ABCDDPP' :['name: abcd3t' ,'IP: 127.12.32.38', 'tags: ALL, APP,PP,  PP1']},
{'Server Type: ABCDDPP' :['name: abcd4t' ,'IP: 127.12.32.39', 'tags: ALL, APP,PP,  PP2']},
{'Server Type: ABCDDPP' :['name: abcd5t' ,'IP: 127.12.32.47', 'tags: ALL, APP,PP,  PP1']},
{'Server Type: ABCDDPP' :['name: abcd6t' ,'IP: 127.12.32.41', 'tags: ALL, APP,PP,  PP2']},
{'Server Type: ABCDDPP' :['name: abcd7t' ,'IP: 127.12.32.42', 'tags: ALL, APP,PP,  PP1']},
{'Server Type: ABCDDPP' :['name: abcd8t' ,'IP: 127.12.32.48', 'tags: ALL, APP,PP,  PP2']},
{'Server Type: ABCDDPP' :['name: abcd9t' ,'IP: 127.12.32.44', 'tags: ALL, APP,PP,  PP1']},
{'Server Type: ABCDDPP' :['name: abcd0t' ,'IP: 127.12.32.49', 'tags: ALL, APP,PP,  PP2']}

Is there any way we can directly convert to yaml so that it could be in the below format:


"Server Type: ABCDDEER"
: 
  - "name: abcd01t"
  - "IP: 127.12.32.52"
  - "tags: ALL, APP,EER, REER1"

  - "name: abcd02t"
  - "IP: 127.12.32.53"
  - "tags: ALL, APP,EER, REER2"

  - "name: abcd03t"
  - "IP: 127.12.32.54"
  - "tags: ALL, APP,EER, REER2"

"Server Type: ABCDDPP"
: 
  - "name: abcd1t"
  - "IP: 127.12.32.36"
  - "tags: ALL, APP,PP,  PP1"

etc

So that the serverTyoe is the header and whatever with same serverType comes inside of it.

Any help will be much appreciated. Thanks very much!


Solution

  • Using yaml module.

    Ex:

    import ast
    import yaml
    
    result = {}
    with open("data.txt") as infile:
        for line in infile:
            d = ast.literal_eval(line.strip().rstrip(","))
            for k, v in d.items():
                result.setdefault(k, []).extend(v)     #groupby header
    
    with open("outfile.yaml", 'w') as yfile:
        yaml.dump(result, yfile)