thecheech
thecheech

Reputation: 2211

reading header in python from csv

Is there a way to inject the header array into the header vector in a more efficient way without using any packages such as csv, pandas, etc...?

data = []
b = 1
with open(datafile, "rb") as f:
    for line in f:
        if b:
            header=line.strip('\n').split(',')
            b = 0
            continue
        entries=line.strip('\n').split(',')
        data.append(dict(zip(header,entries)))
        #print data
return data

Upvotes: 1

Views: 116

Answers (2)

Kei Minagawa
Kei Minagawa

Reputation: 4521

I just rewrite your code using list comprehension. I don't know it is fast or slow. And I think it is not easy to read. Use it just educational purposes.

datafile = "hoge.csv"
l = [line.strip('\n').split(',') for line in open(datafile, "rb")]
data = [dict(zip(l[0],r)) for r in l[1:]]

Upvotes: 0

x3al
x3al

Reputation: 586

If you don't need to go through the same file twice, yielding values is usually better than returning a list.

with open(datafile, "rb") as f:
    header = next(f).strip('\n').split(',')
    for line in f:
        entry=line.strip('\n').split(',')
        yield dict(zip(header,entry))

Upvotes: 1

Related Questions