Reading column names alone in a csv file

前端 未结 9 2300
不思量自难忘°
不思量自难忘° 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:29

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

    • Python's DictReader object in the CSV module (as of Python 2.6 and above) has a public attribute called fieldnames. https://docs.python.org/3.4/library/csv.html#csv.csvreader.fieldnames

    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'])
    

提交回复
热议问题