V
V
Vladislav Shepilov2014-08-12 16:33:25
Python
Vladislav Shepilov, 2014-08-12 16:33:25

How to parse csv by pattern in Python?

How to parse csv is not manual, but "according to the template" so to speak. That is, we have a csv source file, we have an xml, yaml, json template ... we run the file through the template and we get a python object at the output. Are there libs for this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
snowpiercer, 2014-08-12
@snowpiercer

import csv


first = True
header = None
objs = []
for line in csv.reader(open('test_csv', 'r'), delimiter=' '):
    if first :
        header = line
        first = False
    else:
        objs.append(dict(zip(header, line)))

print objs

test_csv file
a b c d e
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15

output:
[{'a': '1', 'c': '3', 'b': '2', 'e': '5', 'd': '4'}, {'a': '6', 'c': '8', 'b': '7', 'e': '10', 'd': '9'}, {'a': '11', 'c': '13', 'b': '12', 'e': '15', 'd': '14'}]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question