I'm just starting with Python, and am working with the following code to import a CSV file into an sqlite3 table, which I freely admit I've copied most of from the internet:
with open(getPathTo('my.csv'), 'r') as csvfile:
reader = csv.DictReader(csvfile)
records = [(row['SEGMENT'], row['Comp 1'], row['Comp 2']) for row in reader]
c.executemany("INSERT INTO comparison (`SEGMENT`, `Comp 1`, `Comp 2`) VALUES (?,?,?);", records)
conn.commit()
It works fine, but I'm repeating this for a lot of files and tables, and I'd like to turn it into a function. What I'm aiming for is something like:
def importCSVToTable(file, table, columns)
But, given a list of columns
, how can I use it in this line:
records = [(row['SEGMENT'], row['Comp 1'], row['Comp 2']) for row in reader]
I'm just a bit thrown by the syntax, I think.