简体   繁体   中英

How to convert a YAML to CSV in python

I have a list of dictionary saved in my log.yml file, I want covert it to a csv to make it look like this在此处输入图像描述

Yaml_to_CSV.py

import csv
import yaml

fieldnames = ['Name', 'IP', 'Comments', 'Subnet4', 'Subnet-Mask']

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

    for filename in ['log.yml']:
        with open(filename) as f_input:
            data = yaml.safe_load(f_input)

I got stuck here.

log.yml

-   comments: FWP - Host 1
    ipv4-address: 10.1.2.3
    name: gTest101
-   comments: FWP - Network 2
    name: gTest102
    subnet-mask: 255.255.255.255
    subnet4: 41.1.2.2

You could use a dictionary to map between the field names in the YAML and the field names in your CSV file:

import csv
import yaml

fields = {
    'name' : 'Name',
    'ipv4-address' : 'IP',
    'comments' : 'Comments',
    'subnet4' : 'Subnet4',
    'subnet-mask' : 'Subnet-Mask',
}

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

    for filename in ['log.yml']:
        with open(filename) as f_input:
            for row_yaml in yaml.safe_load(f_input):
                row_csv = {fields[key] : value for key, value in row_yaml.items()}
                csv_output.writerow(row_csv)

This would produce output.csv as:

Name,IP,Comments,Subnet4,Subnet-Mask
gTest101,10.1.2.3,FWP - Host 1,,
gTest102,,FWP - Network 2,41.1.2.2,255.255.255.255

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM