import openpyxl
wb = openpyxl.load_workbook('example.xlsx')
sheet = wb.active
sheet.columns[1]
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
sheet.columns[1]
TypeError: 'generator' object is not subscriptable
I'm a beginner in Python and this is the first time for me to post my question. I'm stuck with the TypeError above saying, 'generator' object is not subscriptable. I think I exactly typed the code written on a website. The URL of the website is https://automatetheboringstuff.com/chapter12/
Please help me to deal with this error.
That tutorial was designed for an older version of the openpyxl library, 2.3.3. Since then the behaviour of .columns
has changed a little bit -- I'm too lazy to look up exactly when -- and now it produces a generator instead (a lazy object which doesn't actually do any work unless it's asked to.)
If you don't care much about performance, you could call list
on the generator that .columns
returns and then select the appropriate column:
>>> sheet.columns[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'generator' object is not subscriptable
>>> list(sheet.columns)[0]
(<Cell Sheet1.A1>, <Cell Sheet1.A2>, <Cell Sheet1.A3>, <Cell Sheet1.A4>, <Cell Sheet1.A5>, <Cell Sheet1.A6>, <Cell Sheet1.A7>)
>>> list(sheet.columns)[1]
(<Cell Sheet1.B1>, <Cell Sheet1.B2>, <Cell Sheet1.B3>, <Cell Sheet1.B4>, <Cell Sheet1.B5>, <Cell Sheet1.B6>, <Cell Sheet1.B7>)
Or select the column by name:
>>> sheet["A"]
(<Cell Sheet1.A1>, <Cell Sheet1.A2>, <Cell Sheet1.A3>, <Cell Sheet1.A4>, <Cell Sheet1.A5>, <Cell Sheet1.A6>, <Cell Sheet1.A7>)
Or -- and this might be simplest, depending on how much time you want to give to possible other problems you might encounter -- you can just downgrade to 2.3.3.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With