Python - Keyerror

Asked

Viewed 634 times

0

Someone can help me !

I am reading a csv file and then I do an INSERT in Mysql database, but I get the following error

Keyerror: 'id'

I have checked the CSV file several times, the file has all the columns and exactly the same name..

arquivo csv

import csv
import pymysql

# importa o arquivo de acesso ao banco
from config import config

# faz a conexão com o banco de dados
cnx = pymysql.connect(**config, charset='utf8')
cursor = cnx.cursor()

# ler o arquivo csv
input_file = csv.DictReader(open("teste.csv", encoding='utf-8'))

# importa o arquivo csv no banco de dados
for row in input_file:
    cursor.execute("INSERT INTO teste.tabela (id,nome) \
                    VALUES (%s,%s)",(row['id'],row['nome']))
    print("Importando Linhas")
    cnx.commit()
  • Could you add in the question some lines from the csv file?

1 answer

2


Place a "print" inside the for and you will immediately understand what is happening.

Only with the data you have placed, it is not possible to affirm with certainty, but if you have recorded the CSV of a Microsoft Excel in Portuguese, the separator will be the character ;, for example, instead of , - the Python csv module does not use any kind of inference to guess which is the separator.

(You can also check this by opening your CSV file in the programming editor, instead of always opening in the spreadsheet program (i.e. Excel, Libreoffice, Googlesheets) - if this is the case, as it seems, of the separator not being a comma, just inform this in the creation of Dictreader:

input_file = csv.DictReader(open("teste.csv", encoding='utf-8'), delimiter=';')

Browser other questions tagged

You are not signed in. Login or sign up in order to post.