Out of range list index in python

import glob
import xlrd

from xlwt import Workbook

wb = Workbook()

for file_name in glob.glob("foo*.xls"):
    wb_orig = xlrd.open_workbook(file_name)
    for ws_orig in wb_orig.sheets():
        ws = wb.add_sheet('{0} {1}'.format(file_name, ws_orig.name))
        for rx in range(ws_orig.nrows):
            for cx in range(ws_orig.ncols):
                ws.write(rx, cx, ws_orig.cell_value(rx,cx))

wb.save("mefoo.xls")

I tried the above code in many ways to combine multiple excel sheets into one workbook ........ this code gives an error like

Traceback (most recent call last):
  File "E:\my python\Internship\mergestackoverflow.py", line 16, in <module>
    wb.save("mefoo.xls")
  File "C:\Python27\lib\site-packages\xlwt\Workbook.py", line 634, in save
    doc.save(filename, self.get_biff_data())
  File "C:\Python27\lib\site-packages\xlwt\Workbook.py", line 615, in get_biff_data
    self.__worksheets[self.__active_sheet].selected = True
IndexError: list index out of range

please help me resolve this error.

+3
source share
2 answers

The only way to get this IndexError is if there are no sheets in the workbook.

You need to study yours glob.glob("foo*.xls"); it doesn't seem to return files.

+6
source

I found a solution not to use the absolute path in glob.

for file_name in glob.glob("C://your//full//path//here//foo*.xls"):
  #population/merging code here

wb.save("mefoo.xls")

As to why this solved the problem, I don't know. But I hope this helps someone.

+1
source

All Articles