list index out of range when processing a csv file

2

This is the complete line of the CSV file where it gives the error:

21890;BH Telecom (PTT BiH, GSMBIH);Bosnia and Herzegovina

If I send to print the variable split , it puts it here:

21890;BH Telecom (PTT BiH

Where the comma begins (, ). This is my code:

for row in valores_bajo_cabecera:
        cont += 1

        split = row[0].split(';')
        imsi = split[0]
        operador = split[1]
        paiss = split[2]
    
asked by Coloma 12.05.2016 в 05:20
source

2 answers

1

Ideally, you should use the Python csv module. Imagine you have a CSV file like the following:

CAMPO1;CAMPO2;CAMPO3
21890;BH Telecom (PTT BiH, GSMBIH);Bosnia and Herzegovina
21891;BH Telecom (PTT BiH, GSMBIH);Germany
21892;BH Entel;China

You can do something like this:

import csv


archivo = open('archivo.csv')
reader = csv.reader(archivo, delimiter=';')
cabecera = reader.next()
print 'Cabecera:', cabecera

for fila in reader:
    print '-' * 50
    imsi = fila[0]
    operador = fila[1]
    pais = fila[2]
    print 'IMSI:', imsi
    print 'Operador:',  operador
    print 'Pais:', pais
print '-' * 50

The result of the previous code is:

Cabecera: ['CAMPO1', 'CAMPO2', 'CAMPO3']
--------------------------------------------------
IMSI: 21890
Operador: BH Telecom (PTT BiH, GSMBIH)
Pais: Bosnia and Herzegovina
--------------------------------------------------
IMSI: 21891
Operador: BH Telecom (PTT BiH, GSMBIH)
Pais: Germany
--------------------------------------------------
IMSI: 21892
Operador: BH Entel
Pais: China
--------------------------------------------------

Notice that the reader I'm passing the delimiter ; (by default is the comma) and that I'm getting rid of the header before starting the loop with this line:

cabecera = reader.next()
    
answered by 13.05.2016 в 14:32
0

Try to print the variable row [0] before assigning it to the variable split and check that it shows the complete line "21890; BH Telecom (PTT BiH, GSMBIH), Bosnia and Herzegovina" because maybe when you take the value out from row, only the part before the comma takes you:

for row in values_under_header:         cont + = 1

    print(row[0])
    split = row[0].split(';')
    imsi = split[0]
    operador = split[1]
    paiss = split[2]
    
answered by 13.05.2016 в 09:52