Reading column names alone in a csv file

前端 未结 9 2312
不思量自难忘°
不思量自难忘° 2020-12-23 18:58

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

9条回答
  •  臣服心动
    2020-12-23 19:37

    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]
    

提交回复
热议问题