我有一个Python代码,我正在从csv文件读取数据并将其内容推送到MySQL。 我收到上面提到的错误。 代码如下:
csv_data = csv.reader('ga_python_data.csv') csv_data = csv.reader('data.csv') for row in csv_data: cursor.execute('INSERT INTO new (date,sessions) VALUES (%s, %s)',*row)错误是:
TypeError: not enough arguments for format string.I have a python code where I am reading data from csv file and pushing its contents to MySQL. I am getting the above mentioned error. Here is the code:
csv_data = csv.reader('ga_python_data.csv') csv_data = csv.reader('data.csv') for row in csv_data: cursor.execute('INSERT INTO new (date,sessions) VALUES (%s, %s)',*row)The error is:
TypeError: not enough arguments for format string.最满意答案
目前你有一个参数行,但你有两个%s说明符。 你需要在行后添加第二个参数。 在你的情况下,你正在阅读CSV文件中的条目。 从理论上讲,每行总是有两个项目,但是如果您的CSV文件有一个空行,或者其中一行缺少一个条目,则会导致问题。 该脚本只接受包含两个值的行:
import MySQLdb import csv # ...first connect to db and create cursor with open('data.csv', 'rb') as f_data: csv_data = csv.reader(f_data) #header = next(csv_data) # optionally skip over a header line for row in csv_data: if len(row) == 2: cursor.execute('INSERT INTO new (date,sessions) VALUES (%s, %s)', tuple(row))最后,确保您正确打开文件很重要。 在Python 2.x中,文件必须以二进制模式打开。 如果您使用的是Python 3.x,则需要更改该行,如下所示:
with open('data.csv', 'r', newline='') as f_data:Currently you have one argument row but you have two %s specifiers. You need to add the second argument after row. In your case you are reading entries from a CSV file. In theory there should always be two items per row, but if your CSV file has an empty row, or if one of the rows is missing an entry it will cause problems. This script only accepts rows which contain two values:
import MySQLdb import csv # ...first connect to db and create cursor with open('data.csv', 'rb') as f_data: csv_data = csv.reader(f_data) #header = next(csv_data) # optionally skip over a header line for row in csv_data: if len(row) == 2: cursor.execute('INSERT INTO new (date,sessions) VALUES (%s, %s)', tuple(row))Lastly, it is important to ensure you open the file correctly. In Python 2.x, the file must be opened in binary mode. If you are using Python 3.x, you will need to change the line as follows:
with open('data.csv', 'r', newline='') as f_data:更多推荐
发布评论