0
import csv
with open('database.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        print(row['NAME'])

Guys, I have a csv file with the first row as a index, and in linux the code read from row['NAME'] and print only the names form colum NAME, when I run it in windows, it says:

C:\Users\Desktop>python py.py
Traceback (most recent call last):
  File "py.py", line 5, in <module>
    print(row['NAME'])
KeyError: 'NAME'

WHY?

8
  • what's the output (of the first row) of cat database.csv? Commented Jul 20, 2015 at 23:18
  • 2
    does this change if you open database.csv as binary? with open('database.csv', 'rb') as csvfile: Commented Jul 20, 2015 at 23:19
  • You should change the title as it is not a bug. Commented Jul 20, 2015 at 23:48
  • saving the csv file from excel 2010 it give the error, if I use the libreoffice from linux to save it as a csv it works fine and the versions of python are: windows 2.7.10 anda suse 2.7.8. Commented Jul 21, 2015 at 0:44
  • cat database.csv LOC;UH;PAX;DIARIA;IN;OUT;N;VALOR;ISS;TOTAL;CNPJ;RAZAO;CEP;NUMERO;COMPLEMENTO;LOGRADOURO;; 3709868;205;"RAGNARSON;RAGNAR";158;08/06/2015;11/06/2015;3;R$ 474,00;R$ 14,22;R$ 488,22;00.00.000/0000-00;SOUTH NET TURISM� BRASIL LTDA;00000-000;215;BLOCO A - 04 ANDAR;AV MARIA LEBRE AGUIAR;;ASSOCIA��O BRUIHIUH DE HIIUHIOHIJ OUHOIJES Commented Jul 21, 2015 at 0:48

1 Answer 1

3

If you are using the python 2- versions, you need to open the csv with rb, i.e.:

with open('database.csv', 'rb') as csvfile:....

for reference, checkout https://docs.python.org/2/library/csv.html as it includes a part in the reader doc about this.

Sign up to request clarification or add additional context in comments.

1 Comment

based on your comment above where you printed out the csv, where is the NAME field you are trying to look up? I'm assuming that line that ends with ;; is the index line defining columns.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.