Skip to content

Instantly share code, notes, and snippets.

@0racle
Last active April 19, 2017 02:06
Show Gist options
  • Save 0racle/ee9d3704bdf1312894320d02fa03eae9 to your computer and use it in GitHub Desktop.
Save 0racle/ee9d3704bdf1312894320d02fa03eae9 to your computer and use it in GitHub Desktop.
CSV Parse

Given that dis.csv looks like this

Name|Age|DOB|Favourite Color
John|17|12/12/1998|Blue
David|31|15/07/1985|Orange
Michael|11|02/08/2005|Red

Open the file called dis.csv and assign the filehandle to the variable csvfile

with open('dis.csv','r') as csvfile:

You can open files with r, w, r+, or a, being 'read', 'write', 'read-write', and 'append' respectively.

Now that csvfile is a filehandle, python can do stuff with it, like iterate over it like a list.

    for line in csv:
        print(line)

But instead, you can pass the filehandle to the csv library to parse the lines for you

import csv

with open('dis.csv','r') as csvfile:
    for record in csv.DictReader(csvfile, delimiter='|'):
        # Do stuff with record

At this point, the variable record is now a dict (aka hash, aka associative array) which just means, it is now holds a collection of key-value pairs, and looks kinda like this: -

record = {
    "Name"            : "John",
    "Age"             : "25",
    "DOB"             : "12/12/1998",
    "Favourite Color" : "Blue",
}

And you can print value of a record by providing the key, ie

print(record['Favourite Color'])

# OUTPUT: Blue

Then you can start more complex stuff with it

with open('dis.csv','r') as csvfile:
    for record in csv.DictReader(csvfile, delimiter='|'):
        if record['Favourite Color'] == 'Orange':
            print(record['Name'], "likes orange")

# OUTPUT: David likes orange
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment