Skip to content

Instantly share code, notes, and snippets.

@jbnunn
Last active January 1, 2016 06:59
Show Gist options
  • Save jbnunn/8108755 to your computer and use it in GitHub Desktop.
Save jbnunn/8108755 to your computer and use it in GitHub Desktop.
Creates an SQL inserts file based off of a CSV
#! /usr/bin/python
import argparse, getopt, sys
parser = argparse.ArgumentParser(description='Writes SQL inserts based off a CSV file. Assumes values are strings.')
parser.add_argument('file', help='name and location of the file to parse')
parser.add_argument('table', help='table name on which inserts will be based')
parser.add_argument('cols', help='comma-separated value of the columns to write')
args = parser.parse_args()
# Grab num cols in passed args and in file...
csv_num_cols = len((args.cols).split(','))
with open(args.file, "rU") as f:
for line in f:
file_num_cols = len(line.split(','))
break
f.close
# ... then check if those numbers match
if file_num_cols != csv_num_cols:
print 'Your columns (' + str(csv_num_cols) + ') do not match the number of columns (' + str(file_num_cols) + ') in the CSV'
sys.exit
inserts = []
with open(args.file, "rU") as f:
for line in f:
vals = []
ins = "INSERT INTO " + args.table + " (" + args.cols + ") VALUES ("
for v in line.split(","):
vals.append("'" + str(v.strip()) + "'")
ins += ",".join(vals) + ");"
inserts.append(ins)
f.close
print "\n".join(inserts)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment