Quantcast
Channel: Howtos & more …– LANbugs
Viewing all articles
Browse latest Browse all 144

Python: Arbeiten mit YAML Files

$
0
0

YAML ist eine vereinfachte Auszeichnungssprache zur Datenserialisierung. Das Format ist einfach gehalten und ist eine schöne alternative zu XML, JSON usw. Ist auch ein super Format für Configfiles als alternative zu INI Files.

Einfaches YAML File:

variable_str: value
variable_num: 33

list:
  - a
  - b
  - c
  - d

dictionary:
  - list1:
    - a
    - b
    - c
  - list2:
    - a
    - b
    - c

block: |
    block ..................
    block ..................
    block ..................
    block ..................
    block ..................
    block ..................
    block ..................

Testscript:

import yaml
from pprint import pprint

with open("test3.yaml", "r") as f:
    x = yaml.load(f.read())

print "RAW Data:"
pprint(x)
print "----"
print "Block:"
print x['block']
print "Dictionary:"
print x['dictionary']
print "List:"
print x['list']
print "Var String:"
print x['variable_str']
print "Var Num:"
print x['variable_num']

Ausgabe:

RAW Data:
{'block': 'block ..................\nblock ..................\nblock ..................\nblock ..................\nblock ..................\nblock ..................\nblock ..................\n',
 'dictionary': [{'list1': ['a', 'b', 'c']}, {'list2': ['a', 'b', 'c']}],
 'list': ['a', 'b', 'c', 'd'],
 'variable_num': 33,
 'variable_str': 'value'}
----
Block:
block ..................
block ..................
block ..................
block ..................
block ..................
block ..................
block ..................

Dictionary:
[{'list1': ['a', 'b', 'c']}, {'list2': ['a', 'b', 'c']}]
List:
['a', 'b', 'c', 'd']
Var String:
value
Var Num:
33

Python Dictionarys / Listen etc. „dumpen“ in ein YAML File:

import yaml

t = {
    "bubu": {
            "a": "a",
            "b": "b",
            "c": "c",
            "d": "d",
            "e": "e",
            },
    "baba": {
            "a": "a",
            "b": "b",
            "c": "c",
            "d": "d",
            "e": "e",
            }
    }

with open('foobar.yaml', 'w') as f:
    yaml.dump(t, f, default_flow_style=False)

Ausgabe:

bubu:
  a: a
  b: b
  c: c
  d: d
  e: e
baba:
  a: a
  b: b
  c: c
  d: d
  e: e

 

 


Viewing all articles
Browse latest Browse all 144