Reading column names alone in a csv file

2020-05-15 10:38发布

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? Kindly help. Thanks and regards.

标签: python
7条回答
聊天终结者
2楼-- · 2020-05-15 11:26

Thanking Daniel Jimenez for his perfect solution to fetch column names alone from my csv, I extend his solution to use DictReader so we can iterate over the rows using column names as indexes. Thanks Jimenez.

with open('myfile.csv') as csvfile:

    rest = []
    with open("myfile.csv", "rb") as f:
        reader = csv.reader(f)
        i = reader.next()
        i=i[1:]
        re=csv.DictReader(csvfile)
        for row in re:
            for x in i:
                print row[x]
查看更多
登录 后发表回答