Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting Columns of a .csv file and finding their index

Tags:

python

csv

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 ?

like image 699
Stephan Ketterer Avatar asked Nov 01 '22 06:11

Stephan Ketterer


1 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
like image 140
mmachine Avatar answered Nov 13 '22 21:11

mmachine