object is not subscriptable... Error Message? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: object is not subscriptable... Error Message? (/thread-21319.html) |
object is not subscriptable... Error Message? - Shafla - Sep-24-2019 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 subscriptableany idea what i am doing wrong? RE: object is not subscriptable... Error Message? - buran - Sep-24-2019 '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/stable/tutorial.html#accessing-many-cells https://openpyxl.readthedocs.io/en/stable/api/openpyxl.worksheet.worksheet.html#openpyxl.worksheet.worksheet.Worksheet.columns Again it is change in API in 2016 https://openpyxl.readthedocs.io/en/stable/changes.html#a1-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 RE: object is not subscriptable... Error Message? - Shafla - Sep-24-2019 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 subscriptablecould you give me an example of the code i should be inputting to get that output? RE: object is not subscriptable... Error Message? - buran - Sep-25-2019 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] |