forked from gnyers/python-tuesday
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwrite-names-as-csv.py
More file actions
30 lines (25 loc) · 1.02 KB
/
write-names-as-csv.py
File metadata and controls
30 lines (25 loc) · 1.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#!/usr/bin/env python3
import csv
# The CSV data
names='''
name|full_name|group|gendergroup|agegroup
fred|Fred Flintstone|flintstones|m|adults
wilma|Wilma Flintstone|flintstones|f|adults
pebbles|Pebbles Flintstone|flintstones|f|kids
'''
# convert the ``names`` str to a list of lists
data = names.strip() # remove white-space chars from both ends
data = data.split('\n') # split ``str`` into lines, returns a ``list``
data = [ line.split('|') for line in data ] # split all rows into its fields
# the ``data`` variable now points to a list object, each of whose element
# is a list:
# data = [
# ['name', 'full_name', 'group', 'gendergroup', 'agegroup'],
# ['fred', 'Fred Flintstone', 'flintstones', 'm', 'adults'],
# ['wilma', 'Wilma Flintstone', 'flintstones', 'f', 'adults'],
# ['pebbles', 'Pebbles Flintstone', 'flintstones', 'f', 'kids']
# ]
# Now let's write this out to the file ``names.csv``
with open('names.csv', 'wt') as fh:
csv_w = csv.writer(fh, dialect='excel', delimiter='|')
csv_w.writerows(data)