Code Style. YAML
This feature is not available in the Educational edition of PyCharm.
Use this page to configure formatting options for YAML files. When you change these settings, the Preview pane shows how this will affect your code.
Tabs and Indents
In this field, specify the number of spaces to be inserted for each indent level.
Keep indents on empty lines
If this checkbox is selected, PyCharm retains indents on empty lines as if they contained some code. If the checkbox is cleared, PyCharm deletes spaces on empty lines.
Indent sequence value
If selected, YAML sequence values are indented relative to the parent key item.
Wrapping and braces
In this tab, customize the exceptions, brace placement and alignment options that PyCharm will apply to various code constructs on reformatting the source code. Check the results in the Preview pane.
Alignment takes precedence over indentation options.
In this field, specify multiple right margins. You can leave a default value or enter the number of spaces for your margin. If you want to specify several margins, enter numbers separated by comma.
Keep when reformatting
Use the checkboxes to configure exceptions that PyCharm will make when reformatting the source code. For example, by default, the Line breaks checkbox is selected.
If your code contains lines that are shorter than a standard convention, you can convert them by disabling the Line breaks checkbox before reformatting.
Align values in maps
Use this list to specify how PyCharm should align key-value pairs. The available options are:
Do not align : the attributes in sequential lines will be not aligned.
On colon : the attributes in sequential lines will be aligned against the colon.
On value : the attributes in sequential lines will be aligned against the value.
Use these options to specify formatting for the YAML sequence values:
Sequence on new line : if selected, each new sequence inside a nested sequences block is put on a separate line:
Otherwise, nested sequences will be kept on a single line:
Block mapping on new line : if selected, block mappings inside a sequence are put on a separate line:
Otherwise, they are kept on a single line:
Automatically insert hyphen on enter : if selected, PyCharm will automatically hyphenate the next sequence value when you press Enter .
Set from
The link appears in the upper-right corner of the page, when applicable. Click this link and choose the language to be used as the base for the current language code style.
To return to the initial set of code style settings and discard the changes, click Reset .
Как создать файл pycharm yml
В этом руководстве мы узнаем, как использовать библиотеку YAML в Python 3. В последние годы она стала очень популярной благодаря использованию для хранения данных в виде сериализованных файлов конфигурации. Поскольку YAML по сути является форматом данных, библиотека YAML довольно простая, поскольку единственная необходимая функциональность – это возможность анализировать файлы в формате YAML.
В этой статье мы начнем с рассмотрения того, как данные хранятся в файле YAML, а затем загрузим эти данные в объект Python. Наконец, мы узнаем, как сохранить объект Python в файле YAML.
Прежде чем мы двинемся дальше, есть несколько предварительных условий для этого урока. Вы должны иметь базовое представление о синтаксисе Python или иметь хотя бы начальный опыт программирования на каком-либо другом языке.
Установка
Процесс установки YAML довольно прост. Это можно сделать двумя способами, начнем с простого.
Метод 1: через точку
Самый простой способ установить библиотеку YAML в Python – через диспетчер пакетов pip. Если в вашей системе установлен pip, выполните следующую команду, чтобы загрузить и установить YAML:
Метод 2: через источник
Если у вас не установлен pip или у вас возникли проблемы с описанным выше методом, вы можете перейти на исходную страницу библиотеки. Загрузите репозиторий в виде zip-файла, откройте терминал или командную строку и перейдите в каталог, в который загружен файл. Когда вы окажетесь там, выполните следующую команду:
Примеры кода
В этом разделе мы узнаем, как обрабатывать (манипулировать) файлами YAML, начиная с того, как их читать, то есть как загружать их в наш скрипт Python, чтобы мы могли использовать их в соответствии с нашими потребностями.
Чтение файлов
В этом разделе мы увидим, как читать файлы YAML в Python. Начнем с создания двух файлов в формате YAML.
Содержимое первого файла выглядит следующим образом:
Содержимое второго файла выглядит следующим образом:
Вы можете видеть, что файлы fruit.yaml и category.yaml содержат разные типы данных. Первый содержит информацию только об одном объекте, то есть о фруктах, а второй содержит информацию о видах спорта и странах.
Давайте теперь попробуем прочитать данные из двух файлов, которые мы создали с помощью скрипта Python. Метод load() из модуля yaml можно использовать для чтения файлов YAML. Взгляните на следующий скрипт:
В приведенном выше скрипте мы указали yaml.FullLoader в качестве значения для параметра Loader, который загружает полный язык YAML, избегая выполнения произвольного кода. Вместо использования функции загрузки и последующей передачи yaml.FullLoader в качестве значения параметра Loader вы также можете использовать функцию full_load(), как мы увидим в следующем примере.
Давайте теперь попробуем прочитать второй файл YAML аналогичным образом, используя скрипт Python:
Поскольку в файле category.yaml 2 документа, мы выполнили цикл, чтобы прочитать их оба.
Как видно из последних двух примеров, библиотека автоматически обрабатывает преобразование данных в формате YAML в словари и списки Python.
Запись
Теперь, когда мы узнали, как преобразовать файл YAML в словарь Python, давайте попробуем сделать что-то наоборот, то есть сериализовать словарь Python и сохранить его в файл в формате YAML. Для этого воспользуемся тем же словарем, который мы получили в результате нашей последней программы.
Метод dump() принимает словарь Python как первый, а объект File как второй параметр.
После выполнения приведенного выше кода в вашем текущем рабочем каталоге будет создан файл с именем store_file.yaml.
Еще одна полезная функция, которую предлагает библиотека YAML для метода dump(), – это параметр sort_keys. Чтобы показать, что он делает, применим его к нашему первому файлу, то есть fruit.yaml:
В выводе видно, что фрукты отсортированы в алфавитном порядке.
Заключение
В этом кратком руководстве мы узнали, как установить библиотеку Python YAML (pyyaml) для управления файлами в формате YAML. Мы рассмотрели загрузку содержимого файла YAML в нашу программу Python в виде словарей, а также сериализацию словарей и сохранение их ключей. Библиотека довольно краткая и предлагает только основные функции.
Работа с файлами в формате YAML#
YAML (YAML Ain’t Markup Language) — еще один текстовый формат для записи данных.
YAML более приятен для восприятия человеком, чем JSON, поэтому его часто используют для описания сценариев в ПО. Например, в Ansible.
Синтаксис YAML#
Как и Python, YAML использует отступы для указания структуры документа. Но в YAML можно использовать только пробелы и нельзя использовать знаки табуляции.
Еще одна схожесть с Python: комментарии начинаются с символа # и продолжаются до конца строки.
Список#
Список может быть записан в одну строку:
Или каждый элемент списка в своей строке:
Когда список записан таким блоком, каждая строка должна начинаться с — (минуса и пробела), и все строки в списке должны быть на одном уровне отступа.
Словарь#
Словарь также может быть записан в одну строку:
Строки#
Строки в YAML не обязательно брать в кавычки. Это удобно, но иногда всё же следует использовать кавычки. Например, когда в строке используется какой-то специальный символ (специальный для YAML).
Такую строку, например, нужно взять в кавычки, чтобы она была корректно воспринята YAML:
Комбинация элементов#
Словарь, в котором есть два ключа: access и trunk. Значения, которые соответствуют этим ключам — списки команд:
Модуль PyYAML#
Для работы с YAML в Python используется модуль PyYAML. Он не входит в стандартную библиотеку модулей, поэтому его нужно установить:
Работа с ним аналогична модулям csv и json.
Чтение из YAML#
Попробуем преобразовать данные из файла YAML в объекты Python.
Чтение из YAML (файл yaml_read.py):
Формат YAML очень удобен для хранения различных параметров, особенно, если они заполняются вручную.
Python YAML
This tutorial will teach how to work with YMAL data in Python using a PyYAML Module.
After reading this tutorial, you will learn:
- The YAML data format
- How to read and write YAML files in Python using a PyYAML Module.
- How to work with Python’s PyPYML module to serialize the data in your programs into YAML format.
- Deserialize YAML stream and convert it into Python objects
- Convert a YAML file to the other commonly used formats like JSON and XML.
Table of contents
What is YAML?
YAML acronym for Ain’t Markup Language. YAML is a human-friendly data serialization standard for all programming languages. I.e., It is widely used to store data in a serialized format.
It is in simple human-readable format makes which makes it suitable for the Configuration files.
The YAML data format is a superset of one more widely used Markup language called JSON (JavaScript Object Notation).
YAML File
Let us see one sample YAML file to understand the basic rules for creating a file in YAML.
The YAML file is saved with extension yaml or yml .
Data in YAML contains blocks with individual items stored as a key-value pair. A key is generally string, and the value can be any scalars data type like String, Integer or list, array, etc.;
In this tutorial, we use the following YAML file ( Userdetails.yaml )
Let’s understand this YAML file:
- YAML documents start with a — (dash or hyphen) three times
- The values can be of any type; e.g., the phone number is numeric, and the userName is String.
- Indentation is used to indicate the nesting of items inside the TablesList .A hyphen precedes each subitem inside.
- Comments in YAML start with a # .
- The YAML document ends with an optional … and we can have multiple documents inside a single YAML file.
Advantages of YAML
- Readable: The YAML file format doesn’t involve many rules, and only simple indentation is used to identify the individual blocks and documents.
- Support in All Programming Languages: The YAML file is supported in all programming languages. So we can write in one language and can be used in other languages without any modifications.
- Object Serialization: YAML data format is serializable.
PyYAML Module
PyYAML is a YAML parser and emitter for Python. Using the PyYAML module, we can perform various actions such as reading and writing complex configuration YAML files, serializing and persisting YMAL data.
Use it to convert the YAML file into a Python dictionary. Using the PyYAML module, we can quickly load the YAML file and read its content.
Installing PyYAML
There are two ways to install it on your machine. The following are the ways:
- Install using the pip command
- Install via source code (via ZIP file)
Approach 1: Pip Command
PyYAML is available on pypi.org, so you can install it using the pip command.
Open the command prompt and run the below pip command to install the PyYAML module
Approach 2: Install via source code
If pip is not installed or you face errors using the pip command, you can manually install it using source code. Follow the below instructions:
- Open PyYAML GitHub repository
- Click on the code section, and download the ZIP file
- Unpack or Extract the Zip archive
- Open command prompt or terminal
- Change the PyYAML directory where the zip file is extracted.
- Run a python setup.py install command to install PyYAML
Also, we can install PyYAML in Google Colab using the following command.
Python YAML Load – Read YAML File
We can read the YAML file using the PyYAML module’s yaml.load() function. This function parse and converts a YAML object to a Python dictionary ( dict object). This process is known as Deserializing YAML into a Python.
This function accepts either a byte string, a Unicode string, an open binary file object, or an open YAML file object as an argument.
A file or byte-string must be encoded in utf-8, utf-16-be or utf-16-le formats where the default encoding format is utf-8 .
Example:
Output:
There are four loaders available for the load() function
- BaseLoader: Loads all the basic YAML scalars as Strings
- SafeLoader: Loads subset of the YAML safely, mainly used if the input is from an untrusted source.
- FullLoader: Loads the full YAML but avoids arbitrary code execution. Still poses a potential risk when used for the untrusted input.
- UnsafeLoader: Original loader for untrusted inputs and generally used for backward compatibility.
Note: It is always safe to use the SafeLoader with the load() function when the source of the file is not reliable.
Loading Multiple YAML Documents Using load_all()
A single YAML file can contain more than one document. A single document ends with . and the next document starts with — . We can read all the documents together using the load_all() function. Here we have the YAML document with two user records.
The load_all() function parses the given stream and returns a sequence of Python objects corresponding to the documents in the stream.
Example:
Output:
Here we can see that every document is loaded as a Scalar object stream and returns a generator. But we can typecast it to a list and print it.
Loading a YAML Document Safely Using safe_load()
Due to the risk involved in loading a document from untrusted input, it is advised to use the safe_load() .This is equivalent to using the load() function with the loader as SafeLoader .
safe_load(stream) Parses the given and returns a Python object constructed from the first document in the stream. safe_load recognizes only standard YAML tags and cannot construct an arbitrary Python object.
Similar to the safe_load() option available for the load() there is one function called safe_load_all() that is available for the load_all() .
Python YAML Dump – Write into YAML File
Let’s see how to write Python objects into YAML format file.
Use the PyYAML module’s yaml.dump() method to serialize a Python object into a YAML stream, where the Python object could be a dictionary.
Note: The yaml.dump function accepts a Python object and produces a YAML document.
Let’s see the simple example to convert Python dictionary into a YAML stream.
Example:
Output
We can transfer the data from the Python module to a YAML file using the dump() method.
As you know, when the application processes lots of information, It needs to take a data dump. Using dump(), we can translate Python objects into YAML format and write them into YAML files to make them persistent and for future use. This process is known as YAML Serialization.
The yaml.dump() method accepts two arguments, data and stream . The data is the Python object which will be serialized into the YAML stream.
The second optional argument must be an open text or binary file. When you provide the second argument it will write the produced YAML document into the file. Otherwise, yaml.dump() returns the produced document.
Example:
Once the above statements are executed the YAML file will be updated with the new user details.
Also, you can use the safe_dump(data,stream) method where only standard YAML tags will be generated, and it will not support arbitrary Python objects.
There are two tags that are generally used in the dump() method:
- default_flow_style: This tag is used to display the contents of the nested blocks with proper indentation. The default value is True . In that case, the values inside the nested lists are shown in the flow style but setting this tag to False will display the block style’s contents with proper indentation.
- sort_keys: This tag is used to sort the keys in alphabetical order. The default value is true. By setting the tag’s value as false we can maintain the insertion order.
Dump Multiple YAML Documents
You can also dump several YAML documents to a single stream using the yaml.dump_all() function. The dump_all accepts a list or a generator producing Python objects to be serialized into a YAML document. The second optional argument is an open file.
Example:
Output:
Python YAML sorting keys
Using keyword argument sort_keys , you can sort all keys of YAML documents alphabetically. Set sort_keys=True .
Example:
Output:
Pretty Print YAML File
We can format the YAML file while writing YAML documents in it. The dump supports several keyword arguments that specify formatting details for the emitter. For instance, you can set the preferred indentation and width.
Parameter:
- indent : To set the preferred indentation
- width : To set the preferred width
- canonical=True : To force the preferred style for scalars and collections.
Example:
Make Custom Python Class YAML Serializable
Using the PyYAML module you can convert YAML into a custom Python object instead of a dictionary or built-in types. i.e., PyYAML allows you to read a YAML file into any custom Python object.
Also, You can dump instances of custom Python classes into YAML stream.
Example:
Simple Application using PyYAML
Let create a sample application using PyYAML where we will be loading the UserDetails.yaml file that we created and then access the list of tables for that particular user.
We will be using the load() function with the Loader as SafeLoader and then access the values using the keys.
Output:
Custom Tags with PyYAML
We can add application-specific tags and assign default values to certain tags while parsing the YAML file using the load() method.
The steps involved are:
- Define a custom constructor function by passing the loader and the YAML node.
- Call the construct_mapping() method, which will create a Python dictionary corresponding to the YAML node. This method will return a constructor with the dictionary.
- This constructor will be passed to add_constructor() method that converts a node of a YAML representation graph to a native Python object. A constructor accepts an instance of Loader and a node and returns a Python object.
- Now while calling the load() the method, we can pass as many fields as required with the same custom tag defined in the add_constructor() and the fields without values will be assigned default values defined in the __init()__ method.
Output:
The PyYAML module uses the following conversion table to convert Python objects into YAML equivalent. The yaml.dump() method performs the translations when encoding.
YAML Tag | Python Type |
---|---|
!!null | None |
!!bool | bool |
!!int | int |
!!float | float |
!!binary | str ( bytes in Python 3) |
!!timestamp | datetime.datetime |
!!omap , !!pairs | list of pairs |
!!set | set |
!!str | str or unicode ( str in Python 3) |
!!seq | list |
!!map | dict |
YAML and it’s equivalent Python types
YAML Errors
Whenever YAML parser encounters an error condition, it raises an exception: YAMLError or its subclass. Using this error, we can debug the problem. so it is good practice to write your YAML serialization code in the try-except block.
Example:
Tokens
While parsing the YAML document using the scan() method produces a set of tokens that are generally used in low-level applications like syntax highlighting.
Some common tokens are StreamStartToken,StreamEndToken,BlockMappingStartToken,BlockEndToken etc;
Example:
Output:
Python YAML to JSON
While YAML is considered as the superset of JSON(JavaScript Object Notation), it is often required that the contents in one format could be converted to another one. We can convert a YAML file to a JSON file using the dump() method in the Python JSON module.
We first need to open the YAML file in reading mode and then dump the contents into a JSON file.
Python YAML to XML
XML (eXtensible Markup Language) is a Markup language that uses HTML tags to define every record. It is possible to convert the data in XML format to YAML using the XMLPlain module.
obj_from_yaml() method It is used to generate the XML plain obj from the YAML stream or string. The data read from the YAML stream are stored as OrderedDict such that the XML plain object elements are kept in order.
This plain object is given as input to xml_from_obj() method, which is used to generate an XML output from the plain object.
Let us consider the YAML file with the employee details and the code to convert it to the XML file.
Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.
About Vishal
Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!
Related Tutorial Topics:
Python Exercises and Quizzes
Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.
Чтение и запись YAML в файл на Python
В этом уроке мы узнаем, как использовать библиотеку YAML в Python 3. YAML расшифровывается как Еще один язык разметки .
В последние годы он стал очень популярным для его использования при хранении данных в сериализованном виде для конфигурационных файлов. Поскольку YAML по сути является форматом данных, библиотека YAML довольно коротка, поскольку единственная функциональность, требуемая от нее, – это возможность разбора файлов в формате YAML.
В этой статье мы начнем с просмотра того, как данные хранятся в файле YAML, а затем загрузим эти данные в объект Python. Наконец, мы узнаем, как хранить объект Python в файле YAML. Итак, давайте начнем.
Прежде чем мы двинемся дальше, есть несколько предварительных условий для этого урока. Вы должны иметь базовое представление о синтаксисе Python и/или иметь хотя бы начальный опыт программирования на каком-либо другом языке. Кроме того, учебник довольно прост и легок для начинающих.
Установка
Процесс установки YAML довольно прост. Есть два способа сделать это; сначала мы начнем с простого:
Способ 1: Через Трубу
Самый простой способ установить библиотеку YAML в Python-через менеджер пакетов pip . Если в вашей системе установлен pip, выполните следующую команду для загрузки и установки YAML:
Метод 2: Через Источник
Примеры кода YAML
В этом разделе мы узнаем, как обрабатывать (манипулировать) файлами YAML, начиная с того, как их читать, то есть как загружать их в наш скрипт Python, чтобы мы могли использовать их в соответствии с нашими потребностями. Итак, начнем.
Чтение файлов YAML в Python
В этом разделе мы увидим, как читать файлы YAML в Python.
Давайте начнем с создания двух файлов в формате YAML.
Содержимое первого файла выглядит следующим образом:
Содержимое второго файла выглядит следующим образом:
Вы можете видеть, что фрукты.yaml и категории.файлы yaml содержат различные типы данных. Первый содержит информацию только об одном объекте, то есть фруктах, в то время как второй содержит информацию о спорте и странах.
Теперь давайте попробуем прочитать данные из двух файлов, которые мы создали с помощью скрипта Python. Метод load() из модуля yaml можно использовать для чтения файлов YAML. Посмотрите на следующий сценарий:
В приведенном выше скрипте мы указали yaml.Full Loader как значение параметра Loader , который загружает полный язык YAML, избегая выполнения произвольного кода. Вместо того, чтобы использовать функцию load , а затем передавать yaml.В качестве значения параметра Loader можно также использовать функцию full_load () , как мы увидим в следующем примере.
Теперь давайте попробуем прочитать второй файл YAML аналогичным образом с помощью скрипта Python:
Так как в категории есть 2 документа.yaml file, мы запустили цикл, чтобы прочитать их оба.
Как вы можете видеть из последних двух примеров, библиотека автоматически обрабатывает преобразование данных в формате YAML в словари и списки Python.
Написание файлов YAML на Python
Теперь, когда мы узнали, как преобразовать файл YAML в словарь Python, давайте попробуем сделать все наоборот, то есть сериализовать словарь Python и сохранить его в файл формата YAML. Для этого воспользуемся тем же словарем, который мы получили в качестве вывода из нашей последней программы.
Метод dump() принимает словарь Python в качестве первого параметра, а объект File-в качестве второго.
После выполнения приведенного выше кода создается файл с именем store_file.yaml будет создан в вашем текущем рабочем каталоге.
Еще одной полезной функцией, которую библиотека YAML предлагает для метода dump () , является параметр sort_keys . Чтобы показать, что он делает, давайте применим его к нашему первому файлу, то есть fruits.yaml:
Вы можете видеть в выходных данных, что фрукты были отсортированы в алфавитном порядке.
Вывод
В этом кратком руководстве мы узнали, как установить библиотеку YAML Python (pyyaml) для работы с файлами в формате YAML. Мы рассмотрели загрузку содержимого файла YAML в нашу программу Python в виде словарей, а также сериализацию словарей Python в файлы YAML и хранение их ключей. Библиотека довольно коротка и предлагает только основные функциональные возможности.
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.3.11.43304
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Как создать файл pycharm yml
This feature is not available in the Educational edition of PyCharm.
Use this page to configure formatting options for YAML files. When you change these settings, the Preview pane shows how this will affect your code.
Tabs and Indents
In this field, specify the number of spaces to be inserted for each indent level.
Keep indents on empty lines
If this checkbox is selected, PyCharm retains indents on empty lines as if they contained some code. If the checkbox is cleared, PyCharm deletes spaces on empty lines.
Indent sequence value
If selected, YAML sequence values are indented relative to the parent key item.
Wrapping and braces
In this tab, customize the exceptions, brace placement and alignment options that PyCharm will apply to various code constructs on reformatting the source code. Check the results in the Preview pane.
Alignment takes precedence over indentation options.
In this field, specify multiple right margins. You can leave a default value or enter the number of spaces for your margin. If you want to specify several margins, enter numbers separated by comma.
Keep when reformatting
Use the checkboxes to configure exceptions that PyCharm will make when reformatting the source code. For example, by default, the Line breaks checkbox is selected.
If your code contains lines that are shorter than a standard convention, you can convert them by disabling the Line breaks checkbox before reformatting.
Align values in maps
Use this list to specify how PyCharm should align key-value pairs. The available options are:
Do not align : the attributes in sequential lines will be not aligned.
On colon : the attributes in sequential lines will be aligned against the colon.
On value : the attributes in sequential lines will be aligned against the value.
Use these options to specify formatting for the YAML sequence values:
Sequence on new line : if selected, each new sequence inside a nested sequences block is put on a separate line:
Otherwise, nested sequences will be kept on a single line:
Block mapping on new line : if selected, block mappings inside a sequence are put on a separate line:
Otherwise, they are kept on a single line:
Automatically insert hyphen on enter : if selected, PyCharm will automatically hyphenate the next sequence value when you press Enter .
Set from
The link appears in the upper-right corner of the page, when applicable. Click this link and choose the language to be used as the base for the current language code style.
To return to the initial set of code style settings and discard the changes, click Reset .
Магия jinja
Пользовательские macro
How can I create a yaml file from pure python?
After loading the content from the file using yaml.load() , and dump it into a new YAML file, I get this instead:
What is the proper way of building up a YAML file straight from pure python? I don’t want to write string myself. I want to build the dictionary and list.
3 Answers 3
OKay. I just double checked the documentation. We need this at the end of the yaml.dump(data, optional_args)
The fix is this
where dataMap is the source yaml.load() and f is the file to be written to.
Assuming you are using PyYAML as you probably are, the output you show is not copy-paste of what a yaml.dump() generated as it includes a comment, and PyYAML doesn’t write those.
If you want to preserve that comment, as well as e.g the key ordering in the file (nice when you store the file in a revision control system) use ¹:
which gets you exactly the input:
¹ This was done using ruamel.yaml an enhanced version of PyYAML of which I am the author.
Your first and second listings are equivalent, just different notation.
-
The Overflow Blog
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2022 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2022.9.28.30345
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Python YAML: How to Load, Read, and Write YAML
YAML, a recursive acronym for “YAML Ain’t Markup Language”, is a human-readable data serialization language. It is often used for configuration files, but can also be used for data exchange. The most used python YAML parser is PyYAML, a library that allows you to load, parse, and write YAML, much like Python’s JSON library helps you to work with JSON.
This article teaches you how to load, read, and write YAML files with PyYAML. In addition, you’ll learn how to install it on your system, and how YAML compares to alternatives like JSON.
Table of contents
What is YAML?
According to the official site (1) , YAML is a human-friendly data serialization language for all programming languages. YAML is most often used for configuration files, but it’s also used for data exchange.
YAML is easy to write and read for humans, even for non-programmers. At the same time, it’s also easy to parse YAML, especially with Python and the PyYAML library! Its human-friendliness and readability is the biggest advantage YAML has over other formats, like JSON and XML.
These are the most prominent features of YAML:
- You can use comments in YAML files
- You can store multiple documents in one YAML file, with the — separator. A feature often used in Kubernetes definitions.
- It’s easy to read for humans
- It’s easy to parse for computers
1) Fun fact, the official YAML website is written in the form of valid YAML files.
Why use YAML with Python?
If you ask me, YAML is perfect for configuration files. That’s exactly how I, and many other developers, use it the most. Others seem to agree, as many large projects, like Docker and Kubernetes, use YAML to define deployments. It has a richer syntax than the often used alternative, .ini files, but is still nice on the eyes and simple to write and parse.
There are some downsides to using YAML with Python too, though:
- YAML is not part of the standard Python library, while XML and JSON are
- Its dependence on indentation is frustrating sometimes (however, Python developers are used to that, right?)
- It’s perhaps a bit too versatile for simple use-cases, like data exchange of simple objects.
If you’re looking for a good data format for data exchange and storage, I recommend JSON, XML, or other more efficient formats like protocol buffers and Avro.
Installing and importing PyYAML
There are multiple Python packages that can parse YAML data. However, PyYAML is the most prevalent and also the most complete implementation for parsing YAML. PyYAML is not part of the standard Python library, meaning you need to install it with Pip. Use the following command to install PyYAML, preferable in a virtual environment:
On some systems you need to use pip3:
To use PyYAML in your scripts, import the module as follows. Note that you don’t import ‘pyyaml’, but simply ‘yaml’:
Reading and parsing a YAML file with Python
Once we have the YAML parser imported, we can load a YAML file and parse it. YAML files usually carry the extension .yaml or .yml . Let’s work with the following example YAML file, called config.yaml :
Loading, parsing, and using this configuration file is very similar to loading JSON with the Python JSON library. First, we open the file. Next, we parse it with the yaml.safe_load() function. Please note that I changed the output a little to make it more readable for you:
The YAML parser returns a regular Python object that best fits the data. In this case, it’s a Python dictionary. This means all the regular dictionary features can be used, like using get() with a default value.
Here’s the same example, but interactive, so you can experiment with this for yourself:
Parsing YAML strings with Python
You can use yaml.safe_load() to parse all kinds of valid YAML strings. Here’s an example that parses a simple list of items into a Python list:
Parsing files with multiple YAML documents
YAML allows you to define multiple documents in one file, separating them with a triple dash ( — ). PyYAML will happily parse such files too, and return a list of documents. You can do so by using the yaml.safe_load_all() function. This function returns a generator that in turn will return all documents, one by one.
Note that the file needs to be opened as long as you’re reading documents from the YAML, so you have to do your processing within the with clause. Here’s an interactive example that demonstrates this function:
Writing (or dumping) YAML to a file
Although most will only read YAML as a configuration file, it can be very handy to write YAML as well. Example use cases could be:
- Create an initial configuration file with current settings for your user
- To save state of your program in an easy to read file (instead of using something like Pickle)
In the following example, we’ll:
- Create a list with names as we did before
- Save the names to a YAML formatted file with yaml.dump
- Read and print the file, as proof that everything worked as expected
Here’s the same code as a non-interactive example:
Convert YAML to JSON using Python
If you need to convert YAML to JSON, you can simply parse the YAML as we did above. In the next step, you can use the JSON module to convert the object to JSON.
In this example, we open a YAML-based configuration file, parse it with PyYAML, and then write it to a JSON file with the JSON module:
Here’s the same code as a non-interactive example:
Convert JSON to YAML
For the sake of completeness, let’s do the reverse too: convert JSON to YAML:
PyYAML safe_load() vs load()
You will encounter many examples of PyYAML usage where load() is used instead of safe_load() . I intentionally didn’t tell you about the load() function until now. Since most people have a job to do and tend to quickly copy-paste some example code, I wanted them to use the safest method of parsing YAML with Python.
However, if you’re curious about the difference between these two, here’s the short summary: load() is a very powerful function, just like pickle, if you know that function. Both are very insecure methods because they allow an attacker to execute arbitrary code. PyYAML’s load function allows you to serialize and deserialize complete Python objects and even execute Python code, including calls to the os.system library, which can execute any command on your system.
In recent PyYAML versions, the load() function is deprecated and will issue a big fat warning when you use it in an insecure way.
If you’re parsing regular YAML files, like 99% of us do, you should always use safe_load() , since it only contains a subset of the load function. All the scary, arbitrary code execution type of stuff is stripped out.
Addition resources
Here are some resources that you might want to continue with:
Related posts you might like
Python Courses
Are you enjoying this free tutorial? Please also have a look at my premium courses. They offer a superior user experience with small, easy-to-digest lessons and topics, progress tracking, quizzes to test your knowledge, and practice sessions. Each course will earn you a downloadable course certificate.
Python Fundamentals I is a course for beginners that will get you started with Python in no time. Learn all the essentials, test your progress with quizzes and assignments, and bring it all together with the final course project!