Purified and enhanced version:
import csv import sys import time def make_output_fname(): # Thanks to @Andrew: return time.strftime("Bursarcodes_%x_%X.txt").replace("/", "-").replace(":", "-") def main(csv_fname=None, outfname=None, *args): if not csv_fname: # first arg not given - prompt for filename csv_fname = raw_input("Enter .csv file name: ") if not outfname: # second arg not given - use serialized filename outfname = make_output_fname() with open(csv_fname) as inf, open(outfname, "w") as outf: incsv = csv.reader(inf) for row in incsv: outf.write( "insert into bursarcode_lookup(bursarcode, note_id) values ('{0}', '{1}')\n" .format(*row) ) if __name__=="__main__": # pass any command-line arguments to main() main(*sys.argv[1:])
You can also run it from the command line.
Note that if any data items in your csv file contain non-exclusive single quotes ( ' ), you will receive invalid sql code.
source share