Python - "Error: Indexerror: list index out of range"

Asked

Viewed 1,060 times

1

I cannot find the cause of the error. The program runs well, displays all rows in the table, however, this error message appears.

import re
import xlrd

wb = xlrd.open_workbook('exemplo.xls', encoding_override="cp1252", ragged_rows=True) # enconding_override remove o erro de ausência de condificação em XLS antigos.
worksheet = wb.sheet_by_index(0)
n = 1
while worksheet.cell(n,0).value != xlrd.empty_cell.value: # You can detect an empty cell by using empty_cell in xlrd.empty_cell.value
    # Captura o nome completo da paciente na planilha.
    nomecompleto = worksheet.cell(n, 0).value
    # Expressão Regular para isolar o primeiro nome. Utilizar nome.group(0) para eliminar <_sre.SRE_Match object at
    nome = re.search(r'([A-Z]*)\s', nomecompleto)
    # ZENVIA Layout Tipo B: to;message;from
    print(worksheet.cell(n,2).value + ';' + 'Senhora ' + nome.group(0) + 'a CLI confirma sua consulta com o(a) médico(a) ' +
      worksheet.cell(n,3).value + ' no dia ' + worksheet.cell(n,4).value +
      '. Responda gratis S para confirmar ou N para cancelar.' + ';' + 'CLI')
    n = n + 1

Integrates from error:

Traceback (most recent call last):   File "C:/Users/Thiago/Dropbox/Python/PySmartDoctor/readexcel/readexcel.py", line 12, in <module>
    while worksheet.cell(n,0).value != xlrd.empty_cell.value: # You can detect an empty cell by using empty_cell in xlrd.empty_cell.value  File "C:\Users\Thiago\AppData\Local\Programs\Python\Python35-32\lib\site-packages\xlrd\sheet.py", line 401, in cell
    self._cell_types[rowx][colx], IndexError: list index out of range
  • Show the entire error. Stacktrace is always useful for understanding the problem.

  • Done! I just added a few lines in the code and the error is gone. However, I don’t think it’s very pythonic. if n = Worksheet.nrows: break.

1 answer

1

Solution, I placed within the loop the following condition:

 if n >= worksheet.nrows:
        break
  • yes - the point is that worksheet.cell(n,0).value != xlrd.empty_cell.value finds a vaiza cell in the spreadsheet - in the existing part of the spreadsheet, but gives error if you try to access a cell after the end of it. Put this if at the end it works - but it should actually be the condition in the while (possibly combined with and with the expression that is there - it depends on your data)

Browser other questions tagged

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