How can I parse a YAML file in Python

后端 未结 8 1206
醉话见心
醉话见心 2020-11-22 14:54

How can I parse a YAML file in Python?

8条回答
  •  眼角桃花
    2020-11-22 15:18

    Read & Write YAML files with Python 2+3 (and unicode)

    # -*- coding: utf-8 -*-
    import yaml
    import io
    
    # Define data
    data = {
        'a list': [
            1, 
            42, 
            3.141, 
            1337, 
            'help', 
            u'€'
        ],
        'a string': 'bla',
        'another dict': {
            'foo': 'bar',
            'key': 'value',
            'the answer': 42
        }
    }
    
    # Write YAML file
    with io.open('data.yaml', 'w', encoding='utf8') as outfile:
        yaml.dump(data, outfile, default_flow_style=False, allow_unicode=True)
    
    # Read YAML file
    with open("data.yaml", 'r') as stream:
        data_loaded = yaml.safe_load(stream)
    
    print(data == data_loaded)
    

    Created YAML file

    a list:
    - 1
    - 42
    - 3.141
    - 1337
    - help
    - €
    a string: bla
    another dict:
      foo: bar
      key: value
      the answer: 42
    

    Common file endings

    .yml and .yaml

    Alternatives

    • CSV: Super simple format (read & write)
    • JSON: Nice for writing human-readable data; VERY commonly used (read & write)
    • YAML: YAML is a superset of JSON, but easier to read (read & write, comparison of JSON and YAML)
    • pickle: A Python serialization format (read & write)
    • MessagePack (Python package): More compact representation (read & write)
    • HDF5 (Python package): Nice for matrices (read & write)
    • XML: exists too *sigh* (read & write)

    For your application, the following might be important:

    • Support by other programming languages
    • Reading / writing performance
    • Compactness (file size)

    See also: Comparison of data serialization formats

    In case you are rather looking for a way to make configuration files, you might want to read my short article Configuration files in Python

提交回复
热议问题