Extracting columns of a .csv file and finding their index

I have a large csv file and I want to get all the values ​​in it that are stored in certain columns, I know the name.

Somehow I don’t understand how to do this, but I think I'm 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, correctly, I think and gives me the correct values ​​(column indexes)

What do I need to add to my code for it to work?

+4
source share
2 answers
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
+2
source

If you want to print all the values ​​in these columns to FIELDS, then you want:

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   
0
source

All Articles