在Python中读取和写入CSV文件时出错(Error in reading and writing csv file in python)

编程入门 行业动态 更新时间:2024-10-25 18:29:26
在Python中读取和写入CSV文件时出错(Error in reading and writing csv file in python)

我有一个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:

更多推荐

本文发布于:2023-08-07 06:46:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1463154.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   Error   Python   CSV   reading

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!