Python: TypeError: 'generator' object is not subscriptable 解决方法

问题来源:自学书本《python编程快速上手》P222上的例子,代码如下:

import openpyxl, os
os.chdir("D:\\work")
wb = openpyxl.load_workbook("example.xlsx")
sheet = wb.active
print(sheet.columns[1])

运行后,遇到如下的错误,

Traceback (most recent call last):
  File "D:\work\book\book12-3-5error.py", line 5, in <module>
    print(sheet.columns[1])
TypeError: 'generator' object is not subscriptable

经过搜索,在stackOverflow上找到了解决方法。链接地址为:点击打开链接

问题分析:书本上的代码是基于openpyxl 2.3.3. 后续openpyxl版本对.column的方法的方法已有所改进。

可行的解决方法:(1)  借助列表的方法,     list(sheet.columns)[2]

                        (2)借助列字母,           sheet["B"]

以上两种方法得到的都是数据类型都是元组,<class 'tuple'>。

猜你喜欢

转载自blog.csdn.net/weixin_41569319/article/details/80790605