Frank White
Frank White

Reputation: 321

Extracting Columns of a .csv file and finding their index

I have a big csv, file, and i wanna get all the values in it, that are stored in specific columns i know the name of.

Somehow i don't get it how to do it, but i think i am close :(

import codecs
import csv
import json
import pprint
import re


FIELDS = ["name", "timeZone_label", "utcOffset", "homepage","governmentType_label", "isPartOf_label", "areaCode", "populationTotal", 
      "elevation", "maximumElevation", "minimumElevation", "populationDensity", "wgs84_pos#lat", "wgs84_pos#long", 
      "areaLand", "areaMetro", "areaUrban"]

index=[]

with open('/Users/stephan/Desktop/cities.csv', "r") as f:
    mycsv=csv.reader(f)
    results=[]
    headers=None
    for row in mycsv:
        for i, col in enumerate(row):
            if col in FIELDS:
                index.append(i)
        print row[i]    
print index             

My list index, is correct i think and gives me the right values ( column indices)

What do i have to add to my code to make it work ?

Upvotes: 6

Views: 12575

Answers (2)

mmachine
mmachine

Reputation: 926

import csv

with open('/Users/stephan/Desktop/cities.csv', "r") as f:
    mycsv = csv.DictReader(f)
    for row in mycsv:
        for col in FIELDS:
            try:
                print(row[col])
            except KeyError:
                pass

Upvotes: 5

Stewart
Stewart

Reputation: 1899

If you are looking to print out all the values in those columns in FIELDS, what you want to do is:

for row in mycsv:
    for i, col in enumerate(row):
        # If this is the header row entry for one of the columns we want, save its index value
        if col in FIELDS:
            index.append(i)
        # If this is one of the columns in FIELDS, print its value
        elif i in index:
            print col   

Upvotes: 0

Related Questions