Converting CSV (Comma-Separated Values) to YAML (YAML Ain't Markup Language) involves transforming structured tabular data from a CSV format into a more readable, human-friendly data serialization format like YAML. YAML is commonly used for configuration files, data exchange, and more because of its easy-to-read structure.
Why Convert CSV to YAML?
✅ Human-Readable Format: YAML is much more readable than CSV, especially for complex or hierarchical data.
✅ Ease of Integration: YAML is used widely for configuration files (e.g., Docker, Kubernetes), APIs, and data interchange.
✅ Better Structure: YAML supports nested structures and can represent complex data relationships more naturally than CSV.
Example of CSV to YAML Conversion:
CSV Input:
csv
name,age,city
Alice,30,New York
Bob,25,Los Angeles
Charlie,35,Chicago
Converted to YAML Output:
yaml
- name: Alice
age: 30
city: New York
- name: Bob
age: 25
city: Los Angeles
- name: Charlie
age: 35
city: Chicago
How to Convert CSV to YAML:
1. Using Python:
Python has great libraries like PyYAML to convert data to YAML format. Here's how you can convert CSV to YAML using Python.
Install the Required Libraries:
Install the pyyaml library:
bash
pip install pyyaml
Python Code to Convert CSV to YAML:
python
import csv
import yaml
# Read the CSV file
with open('data.csv', mode='r') as file:
csv_reader = csv.DictReader(file)
data = [row for row in csv_reader]
# Convert to YAML format and save
with open('data.yaml', 'w') as yaml_file:
yaml.dump(data, yaml_file, default_flow_style=False, allow_unicode=True)
This script:
Reads the CSV file using csv.DictReader to convert each row into a dictionary.
Uses the yaml.dump() method to convert the list of dictionaries into YAML format.
Saves the YAML output to a file (data.yaml).
2. Manual Conversion:
For smaller datasets, you can manually convert CSV data to YAML by:
Representing each row as a dictionary under a list.
Using indentation to create nested structures in YAML.
For example:
CSV:
pgsql
name,age,city
Alice,30,New York
Bob,25,Los Angeles
Charlie,35,Chicago
Manually convert it to:
yaml
- name: Alice
age: 30
city: New York
- name: Bob
age: 25
city: Los Angeles
- name: Charlie
age: 35
city: Chicago
When to Convert CSV to YAML:
When you need to convert tabular data into a structured, human-readable format.
When you're working with configurations or data exchanges that require YAML.
When you need to represent more complex data or nested structures that go beyond the simplicity of CSV.