Convert YAML to CSV File Using Python 3 and pyyaml


In this article, I’ll teach you how to convert YAML to CSV using Python. The complete source code of the YAML to CSV Python script is given below. It uses Python’s pyyaml module to convert YAML to CSV file.

You can use this YAML to CSV converter on Windows, Mac, and Linux. But, if you want to use it online then you have to host the source code on a server.

Install Dependencies

pip install csv
pip install pyyaml

Convert YAML to CSV Python

import csv
import yaml

fieldnames = ['Name', 'Author', 'Written', 'About', 'Body']

with open('output.csv', 'w', newline='') as f_output:
    csv_output = csv.DictWriter(f_output, fieldnames=fieldnames)

    for filename in ['Test_Co_1.txt', 'Test_Co_2.txt']:
        with open(filename) as f_input:
            data = yaml.safe_load(f_input)

        name = data[0]['Name']

        for entry in data:
            key = next(iter(entry))

            if key.startswith('Note') or key.startswith('Comment'):
                row = {'Name' : name}

                for d in entry[key]:
                    for get in ['Author', 'Written', 'About', 'Body']:
                            row[get] = d[get]
                        except KeyError as e:


Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.