6 January 2009

Starting simple with Python - CSV to SQL

Well, time to learn a new language, and what better than Python? Here's my first attempt at it, to solve a very simple admin task I had to do, which was to change a csv file to a series of SQL updates.

There's just a small bit of logic required; to skip over empty fields, and sanitizing the input, so overall its a really simple piece of code. Ive added some stuff like command like arguments, but of course havent written error checking, nor usage help. What is strange about Python is that its really sensitive to what sort of indents you use. Tabs are not the same as spaces, so please be very careful, else be wary of this infamous error:
IndentationError: unindent does not match any outer indentation level
Here's the code, which I'm sure I'll be referring to in the near future.


import sys
import csv

destinations = csv.reader( open( sys.argv[1], "rU" ) )

for data in destinations:
if (data[1] != ""):
country = data[0].replace( "'", "\\'" )
print "update Country set ShipMethod = '" + data[1] + "' where CountryName = '" + country + "'; "


yk