Python string formatting with percentage (TypeError: not enough arguments for format string)

2024/10/9 12:27:23

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', '')]
Answer

The desired output can be achieved with simple string additions without the need for a string template:

def xing_csv_to_crmDB2(csv_input):query = ''with open(csv_input, 'r', newline='') as csvfile:csv_data = csv.reader(csvfile, delimiter=',', quotechar='"')insert_str = "INSERT INTO table (ID, user, user_version, value, description) VALUES "for row in csv_data:query += '\n' + str(tuple(row))insert_str += query
# do something

this produces the following output:

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', '')

UPDATE: according to @Tomerikoo's idea, an even more simplified version:

def xing_csv_to_crmDB2(csv_input):with open(csv_input, 'r', newline='') as csvfile:csv_data = csv.reader(csvfile, delimiter=',', quotechar='"')insert_str = "INSERT INTO table (ID, user, user_version, value, description) VALUES "for row in csv_data:insert_str += '\n' + str(tuple(row))
# do something

output is still the same.

https://en.xdnf.cn/q/118588.html

Related Q&A

Circles touching edges

I am struggling with a program to tell whether a created disk touches the edge of a predefined box. The parser keeps saying things such asNameError: global name disksdescription is not defined Warning…

How to split data from a merged cell into other cells in its same row of a Python data frame?

I have a sample of a data frame which looks like this: +---+--------------------------------------------------------------------------------------+---------------+--------------------------------------…

Collect data in chunks from stdin: Python

I have the following Python code where I collect data from standard input into a list and run syntaxnet on it. The data is in the form of json objects from which I will extract the text field and feed …

Getting and calculating stuff through tkinter widets

I was wondering how to calculate stuff using tkinter buttons. Im making a simple program to calculate seconds to hours:minutes:seconds. The user inputs an integer using the entry widget on the seconds …

Why does this condition execute to false when it should execute to true?

I have this code in my spider basic.py file:if l.add_xpath(price, //*[@id="price"]/text(),MapCompose(lambda i: i.replace(,, ), float),re = [,.0-9]):l.add_value(available, 1) else:l.add_value(…

Convert nested JSON to CSV in Python 2.7

Have seen a lot of thread but unable to found the solution for mine. I want to convert one nested JSON to CSV in Python 2.7. The sample JSON file is as below:sample.json # My JSON file that mainly cont…

How do I rectify this error: newline is invalid keyword argument for this function

Im currently working with raspberry pi and using DHT11 to read temperature and humidity values every second. I have to save these values into a database in real time. Heres my code that showing sensor …

How to remove substring from a string in python?

How can I remove the all lowercase letters before and after "Johnson" in these strings? str1 = aBcdJohnsonzZz str2 = asdVJohnsonkkkExpected results are as below:str1 = BJohnsonZ str2 = VJohn…

Try to print frame * and diagonal in python

I try to print * in frame and in diagonal .This is what I did:x=10 y=10 def print_frame(n, m, c):print c * mfor i in range(1, n - 1):print c , *(n-2-i),c, *i , c , cprint c * mprint_frame(10, 10, *)T…

How do I have an object rebound off the canvas border?

I am using the canvas widget from tkinter to create an ellipse and have it move around in the canvas. However when the ellipse comes in contact with the border it gets stuck to wall instead of bouncing…