Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

python - Reading column names alone in a csv file

I have a csv file with the following columns:

id,name,age,sex

Followed by a lot of values for the above columns. I am trying to read the column names alone and put them inside a list.

I am using Dictreader and this gives out the correct details:

with open('details.csv') as csvfile:
    i=["name","age","sex"]
    re=csv.DictReader(csvfile)
    for row in re:
        for x in i:
            print row[x]

But what I want to do is, I need the list of columns, ("i" in the above case)to be automatically parsed with the input csv than hardcoding them inside a list.

with open('details.csv') as csvfile:
   
    rows=iter(csv.reader(csvfile)).next()
    header=rows[1:]
    re=csv.DictReader(csvfile)
    for row in re:
        print row
        for x in header:
            
            print row[x]

This gives out an error

Keyerrror:'name'

in the line print row[x]. Where am I going wrong? Is it possible to fetch the column names using Dictreader?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Though you already have an accepted answer, I figured I'd add this for anyone else interested in a different solution-

An implementation could be as follows:

import csv

with open('C:/mypath/to/csvfile.csv', 'r') as f:
    d_reader = csv.DictReader(f)

    #get fieldnames from DictReader object and store in list
    headers = d_reader.fieldnames

    for line in d_reader:
        #print value in MyCol1 for each row
        print(line['MyCol1'])

In the above, d_reader.fieldnames returns a list of your headers (assuming the headers are in the top row). Which allows...

>>> print(headers)
['MyCol1', 'MyCol2', 'MyCol3']

If your headers are in, say the 2nd row (with the very top row being row 1), you could do as follows:

import csv

with open('C:/mypath/to/csvfile.csv', 'r') as f:
    #you can eat the first line before creating DictReader.
    #if no "fieldnames" param is passed into
    #DictReader object upon creation, DictReader
    #will read the upper-most line as the headers
    f.readline()

    d_reader = csv.DictReader(f)
    headers = d_reader.fieldnames

    for line in d_reader:
        #print value in MyCol1 for each row
        print(line['MyCol1'])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...