概述
python yaml YAML stands for YAML Ain’t a Markup Language. It is a recently introduced data serialization format and is very comfortable for human reading and writing. YAML is poised to replace XML and JSON. YAML代表“ YAML不是标记语言”。 它是最近引入的数据序列化格式,非常适合人类读写。 YAML准备取代XML和JSON。 Read this article to know more and learn YAML with Python in a few minutes. 阅读本文以了解更多信息,并在几分钟内学习使用Python的YAML。 These are some of the reasons YAML is popular and is better than other formats such as XML and JSON. 这些是YAML受欢迎并且比XML和JSON等其他格式更好的一些原因。 Despite the positive points highlighted above, It needs IDE support for parsing and emitting. 尽管上面强调了一些积极点,但它仍需要IDE支持才能进行解析和发射。 The use of YAML, in reality, results in the separation of concerns. 实际上,使用YAML导致关注点分离。 It is relatively easier to read & write YAML in Python. However, one can write YAML in simple text files and validate it with many free online validators. 用Python读写YAML相对容易。 但是,您可以在简单的文本文件中编写YAML,并使用许多免费的在线验证器对其进行验证。 Install PyYAML. 安装PyYAML。 Write the smallest YAML. Create a file test.yaml with the following content. 编写最小的YAML。 创建具有以下内容的文件test.yaml。 Keep reading for a complex YAML example. 继续阅读一个复杂的YAML示例。 As soon as you install PyYAML, you can access the yaml package and the power of reading and writing YAML in Python. 一旦安装了PyYAML,就可以访问yaml包以及使用Python读写YAML的功能。 Save this above code as .py file or write these lines in IPython. As soon as a Python interpreter executes the above statements, a below-shown output is displayed. 将以上代码另存为.py文件,或在IPython中编写这些行。 Python解释器执行以上语句后,将立即显示以下显示的输出。 Isn’t that beautiful! Python’s YAML package provides a safe_load method that parses the YAML file and converts it into a dictionary. 没那么漂亮! Python的YAML包提供了safe_load方法,该方法可以解析YAML文件并将其转换为字典。 Read on to learn about YAML format, syntax, and learn more about reading and writing using Python. 继续阅读以了解YAML格式,语法,并了解有关使用Python进行读写的更多信息。 There are ten most important things that one needs to remember while writing YAML files. 编写YAML文件时,需要记住十件最重要的事情。 To begin with a YAML document, one needs to use 要开始使用YAML文档,需要使用 These three dashes are required only when there is more than one document within a single YAML file. 仅当单个YAML文件中有多个文档时,才需要使用这三个破折号。 Key-value pairs — YAML document is like a map in which there are keys and their associated values. Refer to the Hello World example given above. Any information stored in the file follows the below-shown convention. 键值对 -YAML文档就像一个映射,其中包含键及其关联的值。 请参考上面给出的Hello World示例。 文件中存储的所有信息均遵循以下约定。 2. Short texts — Short texts are written, as shown below. 2.短文本 —编写短文本,如下所示。 3. Long texts — Long texts are written using | and >. A block written using | is called a literal block, and a block written with > is called a folded block. 3.长文本 —长文本使用|书写。 和>。 使用|编写的块 被称为文字块,用>编写的块称为折叠块。 4. Numbers — Numbers are written, as shown below. 4.数字 —写入数字,如下所示。 5. Boolean — Boolean is written as true and false 5.布尔值 -布尔值写为true和false So far, the values stored above are scalars. Let us look at the storing collection of values. 到目前为止,上面存储的值是标量。 让我们看一下存储值的集合。 6. Lists — Lists or arrays are written as shown below. 6.列表 -列表或数组如下所示。 7. Nested Maps — Maps can be nested as shown below. 7.嵌套地图 -可以如下图所示嵌套地图 。 8. References — References or anchors are useful when you want to copy an existing structure into a new form without repeating. An example is given below. 8.引用 —当您想将现有结构复制到新表单而不重复时,引用或锚点很有用。 下面给出一个例子。 9. Multiple documents — Three dashes 9.多个文档 -三个破折号 10. Tags — Tags, in YAML, are used to declare types. Examples are given below. 10.标签 -YAML中的标签用于声明类型。 示例如下。 This list, given above, is not exhaustive, and it is always good to look at the following URLs for more. 上面给出的列表并不详尽,因此最好查看以下URL,以获取更多信息。 YAML Documentation YAML文档 YAML History and References YAML历史和参考 Validate YAML 验证YAML Also, head over to git workflow files in Git Actions. These workflow files are written in YAML too. 另外,转到Git Actions中的git工作流文件。 这些工作流文件也是用YAML编写的。 Let us build on the Hello World message above. 让我们以上面的“ Hello World”消息为基础。 Write all examples given above in test.yaml. The YAML file should look like the one shown below. 将上面给出的所有示例都写在test.yaml中。 YAML文件应如下图所示。 Now create a Python file to read the above written yaml. 现在创建一个Python文件以读取上面编写的yaml。 Running the above given script, using Python, results in the following output. 使用Python运行上面给定的脚本,将得到以下输出。 The output shows the list of parsed documents in test.yaml. However, notice that the order of elements in the documents is not preserved. 输出显示了test.yaml中已解析文档的列表。 但是,请注意,未保留文档中元素的顺序。 Let us now write code to dump the above created list to file, and then add the following code to the Python file. 现在让我们编写代码以将上面创建的列表转储到文件中,然后将以下代码添加到Python文件中。 Once the file is written, you can check the contents. It looks like the one shown below. 写入文件后,您可以检查内容。 看起来如下图所示。 Please note that the order of this new YAML file’s elements is not the same as the previous one. Preserving order while reading a YAML document requires one to follow a naming convention for keys or to write a custom constructor. I will write about various ways of doing the same in my next advanced post on YAML in Python. 请注意,此新YAML文件元素的顺序与上一个元素的顺序不同。 在读取YAML文档时保留顺序要求人们遵循键的命名约定或编写自定义构造函数。 在我的下一篇关于YAML in Python的高级文章中,我将介绍各种方法来完成此任务。 It entirely is an individual’s choice to select a format or storing configuration. YAML is gaining traction and is quite popular among DevOps and automation engineers. 选择格式或存储配置完全是个人的选择。 YAML越来越受欢迎,并且在DevOps和自动化工程师中非常受欢迎。 翻译自: https://medium.com/@p4p3rb0y1/python-yaml-tutorial-getting-started-in-a-few-minutes-24b2d51831f3 python yaml 为什么要学习YAML? (Why learn YAML?)
pip install PyYAML
如何创建YAML文件? (How to create a YAML file?)
message: Hello World
安装PyYAML (Install PyYAML)
import yaml
import pprintwith open(“test.yaml”) as f:
yaml_content = yaml.safe_load(f)pprint.pprint(yaml_content){‘message’: ‘Hello, World!’}
YAML语法和格式 (YAML Syntax and format)
---
. All nested elements need to indented using two spaces but you can use one too.---
。 所有嵌套元素都需要使用两个空格缩进,但您也可以使用一个空格。 key: value
description: This is a brief description of something
another description: “This is also a short description with ‘:’ in it.”
55.5 : keys need not be only stringslong description: |This text preserves the line breaks,
as well as the indentation.folded long description: >This is also one way of writing the long text, but
line breaks and indentations will be replaced with single spaces when read.a number: 129804
a scientific notation: 1e + 4
a float: 100.000
an integer: -5.6flag: false
not flag: truesimple list: [1, 2, 3, four, five, “with quotes”]
nested list:
— item 1
— item 2
-
— one
— two
— three
— fourThis:
is a:
nested_map:
key: valuerepeated text: &my_text This text need not be written again
an anchor : *my_text# We can reference the maps tooperson: &person
age: 10# All members below are of the same age
member 1:
<<: *person
name: Johnmember 2:
<<: *person
name: Dave— -
mark the beginning of a new document.— -
标记新文档的开始。 ---
message: Message of document one---
message: Message of document twonot a number: !!str 0.00035# A language type can be written as shownpython tuple: !!python/tuple [10,1]# An example of storing a binary filean image: !!binary |
R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw== 在Python中阅读YAML (Read YAML in Python)
---# document 1message: Hello, Worlda number : 129804a scientific notation: 1e + 4a float : 100.000an integer: -5.6flag: falsenot flag: truean image: !!binary |
R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==python tuple: !!python/tuple [10,1]not a number: !!str 0.00035— -# document 2message: Message of document twosimple list: [1, 2, 3, four, five, “with quotes”]
nested list:
— item 1
— item 2-
— one
— two
— three
— four# lists can also be stored as keysThis:
is a:
nested_map:
key: valuerepeated text: &my_text This text need not be written again
an anchor : *my_text# We can reference the maps tooperson: &person
age: 10# All members below are of the same age
member 1:
<<: *person
name: Johnmember 2:
<<: *person
name: Daveimport yaml
import pprintwith open(“test.yaml”) as f:
documents = list(yaml.load_all(f, Loader=yaml.Loader))pprint.pprint(documents)[{‘a float’: 100.0,
‘a number’: 129804,
‘a scientific notation’: ‘1e + 4’,
‘an image’: b’GIF89ax01x00x01x00x00x00x00!xf9x04x01nx00x01'
b’x01,x00x00x00x00x01x00x01x00x00x02x02Lx01x00;’,
‘an integer’: -5.6,
‘flag’: False,
‘message2’: ‘Hello, World’,
‘not a number’: ‘0.00035’,
‘not flag’: True,
‘python tuple’: (10, 1)},
{‘This’: {‘is a’: {‘nested_map’: {‘key’: ‘value’}}},
‘an anchor’: ‘This text need not be written again’,
‘member 1’: {‘age’: 10, ‘name’: ‘John’},
‘member 2’: {‘age’: 10, ‘name’: ‘Dave’},
‘message’: ‘Message of document two’,
‘nested list’: [‘item 1’, ‘item 2’, [‘one’, ‘two — three — four’]],
‘person’: {‘age’: 10},
‘repeated text’: ‘This text need not be written again’,
‘simple list’: [1, 2, 3, ‘four’, ‘five’, ‘with quotes’]}] 用Python编写YAML (Write YAML in Python)
with open(“out.yaml”, ‘a’) as f:
yaml.dump_all(documents, f, default_flow_style=False)a float: 100.0
a number: 129804
a scientific notation: 1e + 4
an image: !!binary |
R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==
an integer: -5.6
flag: false
message2: Hello, World
not a number: ‘0.00035’
not flag: true
python tuple: !!python/tuple
- 10
- 1
---
This:
is a:
nested_map:
key: value
an anchor: This text need not be written again
member 1:
age: 10
name: John
member 2:
age: 10
name: Dave
message: Message of document two
nested list:
- item 1
- item 2
- — one
— two — three — four
person:
age: 10
repeated text: This text need not be written again
simple list:
- 1
- 2
- 3
- four
- five
- with quotes 摘要 (Summary)
最后
以上就是难过缘分为你收集整理的python yaml_几分钟即可开始使用python yaml教程 为什么要学习YAML? (Why learn YAML?) 如何创建YAML文件? (How to create a YAML file?) 安装PyYAML (Install PyYAML) YAML语法和格式 (YAML Syntax and format) 在Python中阅读YAML (Read YAML in Python) 用Python编写YAML (Write YAML in Python) 摘要 (Summa的全部内容,希望文章能够帮你解决python yaml_几分钟即可开始使用python yaml教程 为什么要学习YAML? (Why learn YAML?) 如何创建YAML文件? (How to create a YAML file?) 安装PyYAML (Install PyYAML) YAML语法和格式 (YAML Syntax and format) 在Python中阅读YAML (Read YAML in Python) 用Python编写YAML (Write YAML in Python) 摘要 (Summa所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复