CSV tutorial

Supose you want to parse the following cities.csv file :

city,population,country
Shanghai,24150000,China
Karachi,23500000,Pakistan
Beijing,21150000,China
Delhi,17838842,India
Lagos,17060307,Nigeria
Istanbul,14160467,Turkey
import csv
csvfile = open('cities.csv')
csvcities = csv.reader(csvfile)
import dum

# define our parser class and run it on our sample of XML
class City:
    class dum:
        name = str,"city"
        country = str
        population = int

for city in dum.csv(City, csvcities):
    print(city.name, city.country, city.population)

If you run this you get :

Shanghai China 24150000
Karachi Pakistan 23500000
Beijing China 21150000
Delhi India 17838842
Lagos Nigeria 17060307
Istanbul Turkey 14160467

Explicit column headers

If the cities.csv file hasn’t a row header:

Shanghai,24150000,China
Karachi,23500000,Pakistan
Beijing,21150000,China
Delhi,17838842,India
Lagos,17060307,Nigeria
Istanbul,14160467,Turkey

You need to pass it to dum.csv

# define our parser class and run it on our sample of XML
class City:
    class dum:
        name = str,"city"
        country = str
        population = int

for city in dum.csv(City, csvcities, headers=["city", "population", "country"]):
    print(city.name, city.country, city.population)

If you run this you get also :

Shanghai China 24150000
Karachi Pakistan 23500000
Beijing China 21150000
Delhi India 17838842
Lagos Nigeria 17060307
Istanbul Turkey 14160467

Table Of Contents

Previous topic

JSON tutorial

Next topic

Reference

This Page