Skip to content

Instantly share code, notes, and snippets.

@szeitlin
Created February 12, 2014 02:01
Show Gist options
  • Save szeitlin/8948612 to your computer and use it in GitHub Desktop.
Save szeitlin/8948612 to your computer and use it in GitHub Desktop.
example from Lynn Root's workshop.
import csv
MY_FILE = "../data/sample_sfpd_incident_all.csv"
#../ means go up one directory
#all caps means a constant variable
def parse(raw_file, delimiter):
""" csv file -> JSON-like object"""
# open csv file
opened_file = open(raw_file) #open is a built-in function in python
# read the csv data
csv_data = csv.reader(opened_file, delimiter=delimiter) #using the csv module we imported
# parse data into python data type
parsed_data = [] #create an empty list (actually will be a dictionary, see below)
fields = csv_data.next() # reads the first line to get the header row
#iterate over the rest of the rows
for row in csv_data:
parsed_data.append(dict(zip(fields, row))) #makes pairs of field:row --> into a dictionary
# close the csv file
opened_file.close() #just to be safe
# return the parsed data
return parsed_data
def main():
"""boilerplate useful if you ever want to turn this into a library"""
new_data = parse(MY_FILE, ",")
print new_data
if __name__== "__main__":
main()
#executes only when you explicitly run this file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment