The following code fails to run.
It goes through a CSV file and retrieves the values and formats them in a array of tuples (a insert query) to be used later. Problem is the csv last column is sometimes a String or nothing (as shown in csv sample below). The error follows. Can anyone help me with this?
def csv_to_DB(csv_input):with open(csv_input, newline='') as csvfile:csv_data = csv.reader(csvfile, delimiter=',', quotechar='"')to_insert = [] # will be list of tuplesinsert_str = "INSERT INTO table (ID, user, user_version, value, description) VALUES "template = "('%s', '%s', '%s', '%s', '%s')"for row in csv_data:to_insert.append(tuple(row)) # convert row/list to tuple and add it to listquery = insert_str + '\n'.join(template % to_insert)#use query for other operations...
CSV sample:
1,aaa,1,0.0,
2,bbb,1,0.13,
3,ccc,1,0.0,
4,ddd,3,1.0,Rom
5,eee,1,0.08,
Error:
query = insert_str + '\n'.join(template % to_insert)
TypeError: not enough arguments for format string
Note: this question is a followup from this question
UPDATE
To clarify: the goal is to create one INSERT with several values instead of several inserts. In this case:
INSERT INTO table (ID, user, user_version, value, description) VALUES
('1', 'aaa', '1', '0.0', ''),
('2', 'bbb', '1', '0.13', ''),
('3', 'ccc', '1', '0.0', ''),
('4', 'ddd', '3', '1.0', 'Rom'),
('5', 'eee', '1', '0.08', '')
to_insert
will be:
[('1', 'aaa', '1', '0.0', ''), ('2', 'bbb', '1', '0.13', ''), ('3', 'ccc', '1', '0.0', ''), ('4', 'ddd', '3', '1.0', 'Rom'), ('5', 'eee', '1', '0.08', '')]