Skip to content

Instantly share code, notes, and snippets.

@mattmc3 mattmc3/csv_to_yaml.py
Last active Sep 30, 2019

Embed
What would you like to do?
Python: csv examples
#!/usr/bin/env python3
import yaml
import csv
data = []
with open('data.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
header=next(csv_reader)
for row in csv_reader:
data.append(dict(zip(header, row)))
print(yaml.dump(data, default_flow_style=True))
print(yaml.dump(data, default_flow_style=False))
#!/usr/bin/env python3
from pprint import pprint
import csv
with open('data.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
header = next(csv_reader)
data = list(csv_reader)
pprint(header)
pprint(data)
from io import StringIO
from pprint import pprint
from collections import namedtuple
import csv
strcsv = '''id,name,skill
1,Mario,Hero
2,Luigi,High Jump
3,Princess,Long Jump
4,Toad,Fast
'''
Character = namedtuple('Character', ['id', 'name', 'skill'])
f = StringIO(strcsv)
reader = csv.reader(f, delimiter=',')
header = next(reader, None)
list_of_dicts = []
list_of_ntuples = []
for row in reader:
list_of_dicts.append(dict(zip(header, row)))
list_of_ntuples.append(Character(*row))
pprint(list_of_dicts)
pprint(list_of_ntuples)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.