python · 1月 23, 2023 0

How to read and write to the YAML file in Python

内容纲要

YAML or YAML Ain’t Markup Language is a case sensitive and human-friendly data serialization language .

For reading and writing to the YAML file, we first need to install the PyYAML package.

$ pip install pyyaml

Creating YAML config file in Python

We can write data to the YAML file using yaml.dump() method.

We are writing the dictionary article_info to the YAML file.

import yaml

article_info = [
    {
        'Details': {
        'domain' : 'www.tutswiki.com',
        'language': 'python',
        'date': '11/09/2020'
        }
    }
]

with open("tutswiki.yaml", 'w') as yamlfile:
    data = yaml.dump(article_info, yamlfile)
    print("Write successful")

File: tutswiki.yaml

- Details:
    date: 11/09/2020
    domain: www.tutswiki.com
    language: python

Note: sort_keys parameter in dump() method can be used to sort the keys in ascending order.

sorted = yaml.dump(data, sort_keys = True)

Reading a key from YAML config file

We can read the data using yaml.load() method .

import yaml

with open("tutswiki.yaml", "r") as yamlfile:
    data = yaml.load(yamlfile, Loader=yaml.FullLoader)
    print("Read successful")
print(data)
Read successful
[{'Details': {'date': '11/09/2020', 'domain': 'www.tutswiki.com', 'language': 'python'}}]

Process finished with exit code 0

Updating a key in YAML config file

import yaml

article_info = [
    {
        'Details': {
        'domain' : 'www.tutswiki.com',
        'language': 'python',
        'date': '11/09/2020'
        }
    }
]

with open("tutswiki.yaml", "r") as yamlfile:
    data = yaml.load(yamlfile, Loader=yaml.FullLoader)
    print(data)
    print("Read successful")
    data[0]['Details']['language'] = 'java'
    print("Value of language updated from 'python' to 'java'")
    yamlfile.close()

with open("tutswiki.yaml", 'w') as yamlfile:
    data1 = yaml.dump(data, yamlfile)
    print(data)
    print("Write successful")
    yamlfile.close()

File: tutswiki.yaml

- Details:
    date: 11/09/2020
    domain: www.tutswiki.com
    language: java
%d 博主赞过: