All pastes #256587 Raw Edit

Anonyme

public text v1 · immutable
#256587 ·published 2006-11-24 12:18 UTC
rendered paste body
#!/usr/bin/python

import sys
import re

setToNullList = ['DATE_TABLEAU']

updateDict = {}

def displayMatrix(matrix):
  for item in matrix:
      print item 

def loadFile (path):
  mat = []
  exp1 = re.compile("INSERT INTO ELECTEUR\(|\);") 
  exp2 = re.compile("\) VALUES \("); 
  for line in file(path,'r'):
    chain=re.sub(exp2,'<****>',re.sub(exp1,'',line)).split('<****>')
    d = dict(zip([i.strip() for i in chain[0].split(',')],[i.strip() for i in chain[1].split(',')]))
    mat.append(d)
  return mat

def updateAttributes (mat,attDict):
  for item in mat:
    item.update(attDict)

def setToNull (mat,attList):
  for myDict in mat:
    for key in attList:
      if myDict[key]=="''":
        myDict[key]='NULL'

def saveToFile (path,mat):
  f=file(path,'w')
  att = ''
  val = ''
  for dict in mat:
    for k,v in dict.items():
      att += k+','
      val += v+','
    sql_rq = 'INSERT INTO ELECTEUR('+att[:len(att)-1]+') VALUES ('+val[:len(val)-1]+');\n'
    print >> f, sql_rq 
    f.flush()
  f.close()   

if __name__ == '__main__':

  if len(sys.argv)==1:
    print "Usage : %s pathin pathout" % (sys.argv[0]) 
  if len(sys.argv)==2:
    mat = loadFile(sys.argv[1])
    #updateAttributes(mat,dict)
    displayMatrix(mat)
    #saveToFile(mat)
  elif len(sys.argv)==3:
    mat = loadFile (sys.argv[1])
    #updateAttributes(mat,updateDict)
    setToNull(mat,setToNullList)
    saveToFile(sys.argv[2],mat)