TypeError:“生成器”对象不可自订
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
我是Python的初学者,这是我第一次发布我的问题。 我坚持与TypeError上面说'发电机'的对象是不可下标的。 我想我确切地input了写在网站上的代码。 该网站的url是https://automatetheboringstuff.com/chapter12/
请帮我处理这个错误。
该教程是为旧版本的openpyxl库2.3.3devise的。 从那以后, .columns
的行为已经改变了一点 – 我懒得查询什么时候 – 现在它产生一个生成器,而不是一个懒惰的对象,实际上没有做任何工作,除非被要求。 )
如果你不关心性能,可以调用.columns
返回的生成器的list
,然后select适当的列:
>>> 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>)
或按名称select列:
>>> sheet["A"] (<Cell Sheet1.A1>, <Cell Sheet1.A2>, <Cell Sheet1.A3>, <Cell Sheet1.A4>, <Cell Sheet1.A5>, <Cell Sheet1.A6>, <Cell Sheet1.A7>)
或者 – 这可能是最简单的,取决于你想要给可能遇到的其他问题多less时间 – 你可以降级到2.3.3。
正如软件包文档中所述,从版本2.4.0开始:
ws.rows和ws.columns现在总是返回生成器,并从工作表顶部开始
所以,如果你想得到第1列,你可以(除了DSM已经build议的方法next()
在生成器上使用next()
函数:
next(sheet.columns)
但是,如果您仍想将openpyxl
降级openpyxl
书中使用的版本,请尝试:
pip install -I openpyxl==2.3.3