Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use PyYAML Library to read and write yaml Files in Python

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the relevant knowledge of "how Python uses PyYAML library to read and write yaml files". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

First, brief introduction to YAML

The abbreviation of YAML,Yet Another Markup Language, which is usually used to write project configuration and can also be used for data storage, is more concise than configuration files such as conf.

Second, YAML grammar

Supported data types:

Dictionaries, lists, strings, Boolean values, integers, floating point numbers, Null, time, etc

Basic grammatical rules:

1. Case sensitivity

2. Use indentation to represent hierarchical relationships

3. Align elements at the same level to the left

4. the key-value pair is represented by a colon ":" structure, and the colon and the value need to be separated by a space.

5. The array is preceded by a "-" symbol, and the symbol and value need to be separated by a space.

6. The value of None can be represented by null and ~

7. Use 3 horizontal bars between multiple sets of data-segmentation

8 # indicates a comment, but you cannot add a # comment at the end of a line of code, otherwise an error will be reported

Note: when I find all kinds of blogs on the Internet, it is mentioned that you can't use the tab key when indenting yaml, but I can use the tab key when I actually use it in the pycharm editor. I didn't report an error when reading and writing!

Third, install the third-party yaml file processing library PyYAML

Python does not have its own library for dealing with yaml files. You need to download the third-party library PyYAML or ruamel.yaml. Here we install PyYAML.

If the download speed of pip install pyyaml# is slow, add Tsinghua image source pip install pyyaml-I https://pypi.tuna.tsinghua.edu.cn/simple 4, read yaml file 1, read dictionary from yaml

The dictionary format in yaml is as follows:

# yaml file, named yamlDataos: AndroidosVersion: 10account: username: xiaoqq password: 123456deviceName: nullappPackage: ~ bool1: True

Read the dictionary code:

# @ author: give you a blank page of import yamlwith open ('. / yamlData.yml', 'rpm, encoding='utf-8') as f: result = yaml.load (f.read (), Loader=yaml.FullLoader) print (result, type (result)) print (result ['os'], type (result [' os']) print (result ['osVersion'], type (result [' osVersion'])) print (result ['account']) Type (result ['account']) print (result [' account'] ['username']) print (result [' deviceName']) print (result ['appPackage']) print (result [' bool1'], type (result ['bool1']))

Read result:

{'os':' Android', 'osVersion': 10,' account': {'username':' xiaoqq', 'password': 123456},' deviceName': None, 'appPackage': None}

Android

ten

{'username':' xiaoqq', 'password': 123456}

Xiaoqq

None

None

True

As can be seen from the reading results:

1. The data read out will not change the original data type, that is, the data type is read out as it is in yaml.

The result will not be affected if the parameter Loaderroomyaml.FullLoader is not written, but a warning message will appear at run time.

3Jing yaml.load (f.read (), Loader=yaml.FullLoader) can also be written as yaml.load (f, Loader=yaml.FullLoader), and the result is the same.

2, read list from yaml

List format in yaml: the data is preceded by'- 'and separated by spaces, as follows:

# yaml file name yamlData- Android- 10-null- ~-True

Read the list code:

# @ author: give you a blank page of import yamlwith open ('. / yamlData.yml', 'ritual, encoding='utf-8') as f: result = yaml.load (f.read (), Loader=yaml.FullLoader) print (result, type (result))

Read result:

['Android', 10, None, None, True]

3, read tuples from yaml

Store tuple format in yaml: used in yaml! Data types are converted, and tuple in yaml is converted from list. As follows:

# yaml file name: yamlDatacompressed python True tuple10-null- ~-True

Read the tuple code:

# @ author: give you a blank page of import yamlwith open ('. / yamlData.yml', 'ritual, encoding='utf-8') as f: result = yaml.load (f.read (), Loader=yaml.FullLoader) print (result, type (result))

Read result:

('Android', 10, None, None, True)

In practical use, many types of nested data are often used. The following yaml data

# yaml file name yamlDataos: AndroidosVersion: 10account:-username1: xiaoqq-password1: 123456-username2: Lilei-password2: 888888deviceName: nullappPackage: ~ bool1: True

Read result:

{'os':' Android', 'osVersion': 10,' account': [{'username1':' xiaoqq'}, {'password1': 123456}, {' username2': 'Lilei'}, {' password2': 888888}], 'deviceName': None,' appPackage': None, 'bool1': True}

4, read multiple groups of data from yaml

When yaml has multiple groups of data, each group of data needs to be separated by 3 horizontal bars, as follows:

Os: AndroidosVersion: 10account1: username1: xiaoqq password1: 123456---os: iososVersion: 12account1: username2: Lilei password2: 888888

When reading multiple sets of data from yaml, you need to use the yaml.load_all () method, return the result as a generator, and use for loop statements to get each set of data. The code is as follows:

# @ author: give you a blank page of import yamlwith open ('. / yamlData.yml', 'ritual, encoding='utf-8') as f: result = yaml.load_all (f.read (), Loader=yaml.FullLoader) print (result, type (result)) for i in result: print (I)

Read result:

{'os':' Android', 'osVersion': 10,' account1': {'username1':' xiaoqq', 'password1': 123456}}

{'os':' ios', 'osVersion': 12,' account1': {'username2':' Lilei', 'password2': 888888}}

Fifth, write yaml file 1, and write a single group of data to yaml file

Using the yaml.dump () method, add the allow_unicode=True parameter to prevent Chinese characters from being written, as follows:

# @ author: give you a blank page import yamlapiData = {"page": 1, "msg": "address", "data": [{"id": 1, "name": "school"}, {"id": 2, "name": "apartment"id": 3, "name": "floating population community"}] } with open ('. / writeYamlData.yml', 'walled, encoding='utf-8') as f: yaml.dump (data=apiData, stream=f, allow_unicode=True)

Write result:

Data:

-id: 1

Name: school

-id: 2

Name: apartment

-id: 3

Name: floating population Community

Msg: address

Page: 1

2, multiple groups of data are written into yaml file

Use the yaml.dump_all () method as follows:

# @ author: give you a blank sheet of paper

Import yaml

ApiData1 = {

"page": 1

"msg": "address"

"data": [{

"id": 1

"name": "School"

}, {

"id": 2

"name": "apartment"

"id": 3

"name": "floating Community"

}]

}

ApiData2 = {

"page": 2

"name": "Hotel

"name": "Hospital"

"name": "nursing home"

With open ('. / writeYamlData.yml', 'walled, encoding='utf-8') as f:

Yaml.dump_all (documents= [apiData1, apiData2], stream=f, allow_unicode=True)

Write result:

Data:

-id: 1

Name: school

-id: 2

Name: apartment

-id: 3

Name: floating population Community

Msg: address

Page: 1

-

Data:

-id: 1

Name: hotel

-id: 2

Name: hospital

-id: 3

Name: nursing home

Msg: address

Page: 2

In Python, in addition to the PyYAML library, there is also a ruamel.yaml library that can also read and write yaml files.

This is the end of the introduction of "how to use the PyYAML library to read and write yaml files in Python". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report