Tuesday, January 06, 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

5 lewsers:

hussein said...

Hey I'm doing python myself atm! :)

Yoon Kit said...

As they say, don't touch anything till it has hit version 3!

[with the exception of DBase III ... which cheated]


yk.

Khairil said...

What editor do you use? I actually haven't seen this error because vim does all the indenting properly automatically.

Yoon Kit said...

I normally use geany. Nice and cheerful editor. It auto indents, and it shouldnt be a problem, it was just that I accidentally added a space in the if statement block, and it caused the problem.

Will try not to do it again!

yk

kedai said...

google xlrd, another good library to do stuff with xls.

and welcome, pythonista
:)