Python – CSV handling

If you are going to process CSV’s in Python, you must really use the csv module. It makes life very easy on you and has extensive possibilities. By default, It creates a dictionary containing the header rows as key (eg: “Header 1”), which makes processing a charm.

import csv

coordinates_file = open("data.csv", "rU")
coordinates_data = csv.DictReader(coordinates_file)

for coord in coordinates_data:
    print (coord["Header 1"])

coordinates_file.close()

In the open statement, the “rU” is for universal read, meaning python will figure out line endings. (\r\n or \n or something other).

Another little trick, is once you have loaded a csv file, you can for example make a indexed array by indexing the input with one of the information in the row (assume here patrols is loaded with all the patrols, either from a DB or a CSV file):

patrols_dict = {} #Init to empty
for patrol in patrols:
     patrols_dict[patrol["PatrolID"]] = patrol

#And now we can access a patrol directly by it's patrol ID
#eg. patrols_dict["1000"] to access patrol 1000.