Python Forum

Full Version: object is not subscriptable... Error Message?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am trying to access values of cells in an exel workbook. i am following an exercise from a book and getting the following error message;
>>> import openpyxl
>>> wb=openpyxl.load_workbook('Example_Page267.xlsx')
>>> sheet=wb.active
>>> sheet.columns[1]
Traceback (most recent call last):
  File "<pyshell#151>", line 1, in <module>
    sheet.columns[1]
TypeError: 'generator' object is not subscriptable
any idea what i am doing wrong?
'Worksheet.columns' is a generator, you cannot subscript it (i.e. use square bracket notation to access elements)
you can iterate over it, or convert it to list/tuple and then use subscript.
https://openpyxl.readthedocs.io/en/stabl...many-cells

https://openpyxl.readthedocs.io/en/stabl...et.columns
Again it is change in API in 2016
https://openpyxl.readthedocs.io/en/stabl...2016-04-11
ws.rows and ws.columns now always return generators and start at the top of the worksheet
Maybe you should find more recent book or carefully check changelog for discrepancies
thank you for the link. I have reviewed and am unable to find the details i am looking for. I am following an exercise in a book called Automate the boring stuff. i am following the exercise exactly and typing the following code
>>> import openpyxl
>>> wb=openpyxl.load_workbook('Example_Page267.xlsx')
>>> sheet=wb.active
>>> sheet.columns[1]

the output the book is saying i should get is
(<cell Sheet1.B1>,<cell Sheet1.B2>,<cell Sheet1.B3>,<cell Sheet1.B4>,<cell Sheet1.B5>,<cell Sheet1.B4>,<cell Sheet1.B5>,<cell Sheet1.B6>,<cell Sheet1.B7>)
but instead i am getting the error message
Traceback (most recent call last):
  File "<pyshell#160>", line 1, in <module>
    sheet.columns[1]
TypeError: 'generator' object is not subscriptable
could you give me an example of the code i should be inputting to get that output?
In the first link I provided it shows you can convert it to tuple and display all of it. In your snippet you want to get just the element with index 1.
>>>tuple(sheet.columns)[1]