Tutorials

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

app.py

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)
    csv_output.writeheader()

    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']:
                        try:
                            row[get] = d[get]
                        except KeyError as e:
                            pass

                csv_output.writerow(row)
Furqan

Well. I've been working for the past three years as a web designer and developer. I have successfully created websites for small to medium sized companies as part of my freelance career. During that time I've also completed my bachelor's in Information Technology.

Recent Posts

Llama 3.1 vs GPT-4 Benchmarks

We evaluated the performance of Llama 3.1 vs GPT-4 models on over 150 benchmark datasets…

July 24, 2024

Transforming Manufacturing with Industrial IoT Solutions and Machine Learning

The manufacturing industry is undergoing a significant transformation with the advent of Industrial IoT Solutions.…

July 6, 2024

How can IT Professionals use ChatGPT?

If you're reading this, you must have heard the buzz about ChatGPT and its incredible…

September 2, 2023

ChatGPT in Cybersecurity: The Ultimate Guide

How to Use ChatGPT in Cybersecurity If you're a cybersecurity geek, you've probably heard about…

September 1, 2023

Add Cryptocurrency Price Widget in WordPress Website

Introduction In the dynamic world of cryptocurrencies, staying informed about the latest market trends is…

August 30, 2023

Best Addons for The Events Calendar Elementor Integration

The Events Calendar Widgets for Elementor has become easiest solution for managing events on WordPress…

August 30, 2023